PHP提示Cannot modify header information - headers already sent by解決方案_php技巧

來源:互聯網
上載者:User

本文執行個體講述了PHP提示Cannot modify header information - headers already sent by解決方案,是進行PHP程式設計過程中經常會遇到的問題。本文對此以執行個體形式分析解決方案。分享給大家供大家參考。具體方法如下:

現來看看這段代碼:

<?php ob_start();setcookie("username","test",time()+3600);echo "the username is:".$HTTP_COOKIE_VARS["username"]."\n";echo "the username is:".$_COOKIE["username"]."\n";print_r($_COOKIE);?>

訪問該PHP檔案時提示Warning: Cannot modify header information - headers already sent by

出錯的原因:

原因是在php程式的頭部加了,header("content-type: text/html; charset=utf-8");之後頁面就出現上面的錯誤。

因為 header('Content-Type:text/html;charset= UTF-8');發送頭之前不能有任何輸出,空格也不行,你需要將header(...)之前的空格去掉,或者其他輸出的東西去掉,如果他上面include其他檔案了,你還要檢查其他檔案裡是否有輸出。

上網查了一些資料,說是我的php.ini裡面的配置出了問題,找到php.ini檔案中的output_buffering預設為off的,把它改為on或者任意一個數字,但嘗試無結果。

setcookie函數必須在任何資料輸出至瀏覽器前,就先送出
基於上面這些限制,所以執行setcookie()函數時,常會碰到"Undefined index"、"Cannot modify header information - headers already sent by"…等問題,解決"Cannot modify header information - headers already sent by"這個錯誤的方法是在產生cookie前,先延緩資料輸出至瀏覽器,因此,您可以在程式的最前方加上ob_start()函數。

ob_start()函數用於開啟緩衝區,比如header()函數之前如果就有輸出,包括斷行符號\空格\換行\都會有"Header had all ready send by"的錯誤,這時可以先用ob_start()開啟緩衝區PHP代碼的資料區塊和echo()輸出都會進入緩衝區而不會立刻輸出!

通過以下方法,問題得到解決:

//在header()之前ob_start(); //開啟緩衝區 echo \"Hellon\"; //輸出 header("location:index.php"); //把瀏覽器重新導向到index.php ob_end_flush();//輸出全部內容到瀏覽器 ?>

希望本文所述對大家PHP程式設計的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.