ob_start();
setcookie("username","宋岩賓",time()+3600);
echo "the username is:".$HTTP_COOKIE_VARS["username"]."\n";
echo "the username is:".$_COOKIE["username"]."\n";
print_r($_COOKIE);
?>
Warning: Cannot modify header information - headers already sent by出錯的原因
我在php程式的頭部加了,
header("cache-control:no-cache,must-revalidate");
之後頁面就出現上面的錯誤,看了N個資料也沒有結果。今天偶爾發現原來是我的php.ini裡面的配置出了問題,在C:\windows\下找到php.ini檔案
output_buffering預設為off的。我現在把它設為4096就OK了。
用於解決顯示提示錯誤,不能按(日期+匯出檔案數)為檔案名稱的錯誤資訊.
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()輸出都會進入緩衝區而不會立刻輸出.當然開啟緩衝區的作用很多,只要發揮你的想象.可以總結以下四點:
1.用於header()之前
ob_start(); //開啟緩衝區
echo \"Hellon\"; //輸出
header("location:index.php"); //把瀏覽器重新導向到index.php
ob_end_flush();//輸出全部內容到瀏覽器
?>
2.phpinfo()函數可擷取用戶端和伺服器端的資訊,但要儲存用戶端資訊用緩衝區的方法是最好的選擇.
ob_start(); //開啟緩衝區
phpinfo(); //使用phpinfo函數
$info=ob_get_contents(); //得到緩衝區的內容並且賦值給$info
$file=fopen(\'info.txt\',\'w\'); //開啟檔案info.txt
fwrite($file,$info); //寫入資訊到info.txt
fclose($file); //關閉檔案info.txt
?>
3.靜態頁面技術
ob_start();//開啟緩衝區
?>
php頁面的全部輸出
$content = ob_get_contents();//取得php頁面輸出的全部內容
$fp = fopen("output00001.html", "w"); //建立一個檔案,並開啟,準備寫入
fwrite($fp, $content); //把php頁面的內容全部寫入output00001.html,然後……
fclose($fp);
?>
4.輸出代碼
Function run_code($code) {
If($code) {
ob_start();
eval($code);
$contents = ob_get_contents();
ob_end_clean();
}else {
echo "錯誤!沒有輸出";
exit();
}
return $contents;
}
http://www.bkjia.com/PHPjc/319672.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/319672.htmlTechArticle?php ob_start(); setcookie("username","宋岩賓",time()+3600); echo "the username is:".$HTTP_COOKIE_VARS["username"]."\n"; echo "the username is:".$_COOKIE["username"]."\n"; print_...