<?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();//輸出全部內容到瀏覽器
?>