找回密碼
 註冊
搜索
查看: 1803|回復: 0

[教學] setcookie 出現Warning: Cannot modify header information

[複製鏈接]
發表於 2012-8-1 17:30:49 | 顯示全部樓層 |閱讀模式
 
Push to Facebook
setcookie 出現 Warning:
Cannot modify header information - headers already sent by

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


範例如下:
index.php


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

  6.     </head>
  7.     <body>
  8.      <?php
  9.      $value = 'something from somewhere';

  10.      setcookie("TestCookie", $value);
  11.      ?>
  12.     </body>
  13. </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必須滿足條件再所有訊息未發出之前就必須設定
如:

  1. <?php
  2. $value = 'something from somewhere';
  3. setcookie("TestCookie", $value);
  4. ?>
  5. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> ....
複製代碼


2.程式檔案最上面加上ob_start();及最下面加上ob_end_flush();
如:

  1. <?php
  2. ob_start();
  3. // Initiate the output buffer
  4. ?>
  5. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title></title>
  10. </head>
  11. <body>
  12. <?php
  13. $value = 'something from somewhere';
  14. setcookie("TestCookie", $value);
  15. ?>
  16. </body>
  17. </html>
  18. <?php
  19. ob_end_flush();
  20. // Flush the output from the buffer
  21. ?>
複製代碼


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


這樣就可以解決問題了
 
您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

Archiver|手機版|小黑屋|TShopping

GMT+8, 2025-6-16 12:14 , Processed in 0.020804 second(s), 17 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回復 返回頂部 返回列表