程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> Cannot modify header information錯誤解決方法

Cannot modify header information錯誤解決方法

編輯:PHP綜合
<?php
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;
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved