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");之後頁面就出現上面的錯誤。上網查了一些資料,說是我的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();//輸出全部內容到瀏覽器
?>