關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • PHP 的 "Header already sent" 錯誤

    Posted on May 6th, 2007 Sam Tang 2 comments

    使用 header() 可以向 browser 發出 header 資訊,可以實現轉址或強制 browser 不要將頁面快取等。很多學習 PHP 的朋友也會遇過 "Header already sent" 錯誤,這個錯誤在使用 header() 或 session_start() 這類 functions 時,如果之前輸出過任何內容便會產生,即使是 html tag, 空字串或者空行也會一樣。例如:

    PHP:
    1. <?php
    2. ?>
    3. <html>

    以上語句沒有問題,但如果改用以下方式表達便會出現錯誤:

    PHP:
    1. <HTML>
    2. <?php
    3. ?>

    以上問題的其中一個解決方法是在使用 session_start() 前加入 ob_start();


     

    2 responses to “PHP 的 "Header already sent" 錯誤”

    1. Hi~~你好

      想請教您一個問題

      小弟剛開始學習PHP,現有以下一問題

      上傳測試程式後

      在 gd_info 下GD Version —-2.0.34 compatible

      在 PHP + GD Library 繪圖測試程式

      <?php
      header (“Content-type: image/png”);

      $im = @imagecreate (500, 400) or die (“Cannot Initialize new GD image stream”);
      $background_color = imagecolorallocate ($im, 0, 196, 0);
      $text_color = imagecolorallocate ($im, 255, 255, 0);
      $pen_color = imagecolorallocate($im, 255, 255, 255);

      imagestring ($im, 2, 160, 35, “OK ! You can draw graph in PHP !”, $text_color);
      imageline($im, 1, 1, 500, 400, $pen_color);
      imageline($im, 500, 1, 1, 400, $pen_color);
      imageellipse($im, 250, 200, 200, 200, $pen_color);
      imageellipse($im, 250, 200, 240, 240, $pen_color);
      imagepng ($im);
      ?>

      卻出現
      Warning: Cannot modify header information – headers already sent by

      和一堆亂碼

      請問如何解決呢???

    2. 因為輸出圖片前曾經輸出其他內容,那便會有 “headers already sent” 錯誤,其中空格及空行等看不見的字符也一樣。

    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word