woff 發表於 2012-8-1 17:30:49

setcookie 出現Warning: Cannot modify header information

setcookie 出現 Warning:
Cannot modify header information - headers already sent by

SESSION及COOKIE真的很龜毛,兩各規則卻相反,但是又不得不用,只好想辦法處理了


範例如下:
index.php


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title></title>

    </head>
    <body>
   <?php
   $value = 'something from somewhere';

   setcookie("TestCookie", $value);
   ?>
    </body>
</html>
但是IE8出現
Warning:
Cannot modify header information - headers already sent by
(output started at C:\xampp\htdocs\test\index.php:9)
in C:\xampp\htdocs\test\index.php on line 12



這解決方法有三種
1.COOKIE必須滿足條件再所有訊息未發出之前就必須設定
如:

<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> ....

2.程式檔案最上面加上ob_start();及最下面加上ob_end_flush();
如:
<?php
ob_start();
// Initiate the output buffer
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value);
?>
</body>
</html>
<?php
ob_end_flush();
// Flush the output from the buffer
?>

第三種
修改php.ini(前提是有管理權限)
output_buffering = On

這樣就可以解決問題了
頁: [1]
查看完整版本: setcookie 出現Warning: Cannot modify header information