<?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();//輸出所有內容到瀏覽器
?>
版權聲明:本文博客原創文章,博客,未經同意,不得轉載。