PHPのエラー『Notice: Header Information Cannot Be Modified After』の解決方法

  • 作成日 2025.03.29
  • php
PHPのエラー『Notice: Header Information Cannot Be Modified After』の解決方法

PHPで `header()` 関数を使ってリダイレクトやクッキーの設定を行う際に、「Notice: Header Information Cannot Be Modified After」というエラーが発生することがある。このエラーの発生条件と解決方法を詳しく説明する。

1. エラーの発生条件

このエラーは、主に次のような状況で発生する。

  • すでにHTMLや空白を出力した後に `header()` を実行している
  • `header()` を `echo` や `print` の後に実行している
  • インクルードされたファイルに空白や改行が含まれている
  • 出力バッファリングが有効でない状態でエラーが発生している

2. エラーが発生するコード例

次のコードは、このエラーを引き起こす典型的な例。

<?php
echo "Hello, world!";
header("Location: https://example.com");
?>

このコードを実行すると、次のようなエラーが発生する。

Warning: Cannot modify header information - headers already sent by (output started at /path/to/script.php:1) in /path/to/script.php on line X

3. 解決策1: `header()` の前に出力を行わない

`header()` の前に `echo` や `print` などの出力を行わないようにする。

<?php
header("Location: https://example.com");
exit;
?>

4. 解決策2: `exit;` を追加する

`header()` の後に `exit;` を入れることで、余計な出力を防ぐことができる。

<?php
header("Location: https://example.com");
exit;
?>

5. 解決策3: ファイルの先頭に余計な空白や改行がないか確認する

PHPファイルの先頭や末尾に空白や改行があると、意図しない出力が発生することがある。

<?php
header("Location: https://example.com");
exit;
?>

6. 解決策4: `include` や `require` で読み込むファイルを確認する

`include` や `require` で読み込んでいるファイルに不要な空白や出力があると、`header()` に影響を与える。

<?php
include 'config.php'; // config.php の中で余計な出力がないか確認する
header("Location: https://example.com");
exit;
?>

7. 解決策5: `ob_start()` を使用する

出力バッファリングを有効にすると、スクリプトの実行が完了するまで出力が抑制される。

<?php
ob_start();
header("Location: https://example.com");
exit;
ob_end_flush();
?>

8. 解決策6: `session_start()` の前に出力しない

セッションを開始する前に出力を行うと、同様のエラーが発生する。

<?php
session_start();
header("Location: https://example.com");
exit;
?>

9. 解決策7: `setcookie()` を `header()` より前に実行する

`setcookie()` もヘッダー情報を変更する関数なので、`header()` より前に実行する必要がある。

<?php
setcookie("user", "JohnDoe", time() + 3600, "/");
header("Location: https://example.com");
exit;
?>

10. 解決策8: HTMLを後回しにする

スクリプトの実行後にHTMLを出力することで、`header()` に影響を与えないようにできる。

<?php
header("Location: https://example.com");
exit;
?>
<!DOCTYPE html>
<html>
<head>
    <title>Redirecting...</title>
</head>
<body>
<p>リダイレクト中...</p>
</body>
</html>