6.

PHP よくあるエラー集と対処完全ガイド(Fatal/Parse/Memory/Undefined)

編集
この記事の要点
  • PHP の代表的エラー: Fatal error / Parse error / Allowed memory size exhausted / Undefined index/variable / Headers already sent / Class not found
  • PHP 8 以降、Undefined variable / Undefined indexE_NOTICE から E_WARNING へ昇格 (PHP 8.0)
  • php.inimemory_limiterror_reporting を理解すれば 8 割解決
  • 本番では display_errors=Off + log_errors=On + error_log 必須
  • Composer autoload が原因の Class not foundcomposer dump-autoload で再生成

PHP のエラー分類

PHP のエラーは大きく分けて パースエラー (Parse error)致命的エラー (Fatal error)警告 (Warning)通知 (Notice)Deprecated の 5 種類があります。PHP 7 と PHP 8 では昇格度合いが異なるので注意が必要です。

分類意味スクリプト継続
E_PARSE構文解析エラー停止 (実行されない)
E_ERROR致命的な実行時エラー停止
E_WARNING警告継続
E_NOTICE通知レベル継続
E_DEPRECATED非推奨機能の使用継続
E_USER_ERRORユーザ定義エラーtrigger_error() で発火

1. Fatal error: Call to undefined function

Fatal error: Uncaught Error: Call to undefined function mb_strlen() in /var/www/index.php:10

原因: 関数が存在しない or 拡張モジュール未インストール。

  • mb_strlen() なら mbstring 拡張が未インストール
  • curl_init() なら php-curl パッケージ未導入
  • 自前関数のスペルミス / ファイル未 require
  • 名前空間ミス (use 忘れ or FQCN ミス)
# 拡張モジュール確認
php -m | grep -i mbstring

# Ubuntu/Debian で追加
sudo apt install php-mbstring php-curl php-xml php-gd
sudo systemctl restart php8.2-fpm

# 関数の存在確認
php -r 'var_dump(function_exists("mb_strlen"));'

2. Parse error: syntax error, unexpected ...

Parse error: syntax error, unexpected token ";", expecting "," or ")" in /var/www/index.php on line 15

原因: 構文ミス。多くはカンマ漏れ / セミコロン漏れ / 閉じカッコの不一致

// NG: 配列の末尾以外のカンマ漏れ
$arr = [
    'a' => 1
    'b' => 2,  // 上の行に , が無い
];

// NG: 文字列内の引用符エスケープ漏れ
$sql = "SELECT * FROM users WHERE name = 'O'Brien'"; // ' で閉じてしまう

// 確認コマンド
// php -l index.php  → No syntax errors detected または該当行

3. Allowed memory size of N bytes exhausted

Fatal error: Allowed memory size of 134217728 bytes exhausted
(tried to allocate 20480 bytes) in /var/www/index.php on line 30

原因: PHP プロセスが memory_limit を超えるメモリを要求。大量のデータ読込・無限ループ的な配列追記など。

; php.ini で全体設定
memory_limit = 256M
// スクリプト内で個別設定
ini_set('memory_limit', '512M');

// 大量データはストリーミング処理に
$fp = fopen('huge.csv', 'r');
while (($row = fgetcsv($fp)) !== false) {
    // 1 行ずつ処理 (全件読み込みは禁忌)
}
fclose($fp);

// Eloquent で chunk() を使う
User::chunk(1000, function ($users) {
    foreach ($users as $user) { /* ... */ }
});

4. Undefined index / Undefined variable

// PHP 7
Notice: Undefined index: name in /var/www/index.php on line 8

// PHP 8
Warning: Undefined array key "name" in /var/www/index.php on line 8
Warning: Undefined variable $foo in /var/www/index.php on line 12

PHP 8 で E_NOTICEE_WARNING に昇格しました。本番でエラーが顕在化しやすくなったので、Null 合体演算子で対処します:

// NG
$name = $_POST['name'];

// OK (Null Coalescing - PHP 7+)
$name = $_POST['name'] ?? '';

// OK (isset 判定)
$name = isset($_POST['name']) ? $_POST['name'] : '';

// 配列ヘルパー
$name = data_get($_POST, 'user.name', '');  // Laravel

5. Headers already sent by ...

Warning: Cannot modify header information - headers already sent by
(output started at /var/www/header.php:3) in /var/www/login.php on line 10

原因: header()setcookie()session_start() より前に何かが出力された (空白、BOM、echo、HTML タグ)。

  • PHP ファイル先頭の BOM 付き UTF-8 が出力扱いされる → BOM 無し UTF-8 で保存
  • ?> 閉じタグの後ろの空白や改行 → 閉じタグ自体を省略すれば防げる
  • 意図しない echo / print_r のデバッグ残骸
<?php
// NG: 出力後にヘッダ
echo "Hello";
header('Location: /next');  // ← 既に echo で出力済

// OK: ob_start() で出力バッファ
ob_start();
echo "Hello";
header('Location: /next');
ob_end_flush();

6. Class not found (autoload)

Fatal error: Uncaught Error: Class "App\Services\UserService" not found

原因: Composer のオートロードが効いていない。

# autoload 再生成
composer dump-autoload -o

# PSR-4 設定確認 (composer.json)
# "autoload": {
#     "psr-4": {
#         "App\\": "src/"
#     }
# }

# 名前空間とディレクトリの対応確認
# App\Services\UserService → src/Services/UserService.php

7. Maximum execution time of N seconds exceeded

Fatal error: Maximum execution time of 30 seconds exceeded
in /var/www/index.php on line 50
// php.ini
// max_execution_time = 60

// スクリプト内
set_time_limit(120);  // 120 秒に延長
set_time_limit(0);    // 無制限 (CLI 推奨)

// CLI なら -d で
// php -d max_execution_time=0 batch.php

8. Cannot redeclare function/class

Fatal error: Cannot redeclare function foo() (previously declared in /var/www/a.php:3)
in /var/www/b.php on line 3

原因: 同じ関数 / クラスを 2 回 require した。require_once / include_once を使うか、関数を function_exists() でガードします。

9. Trying to access array offset on null

// PHP 7.4 / 8.0+
Warning: Trying to access array offset on null
in /var/www/index.php on line 20
// NG
$user = null;
echo $user['name'];  // null は配列じゃない

// OK
echo $user['name'] ?? 'guest';

// OK (Null Safe Operator - PHP 8.0+)
echo $user?->name ?? 'guest';

php.ini の重要設定

; 開発環境
display_errors = On
display_startup_errors = On
error_reporting = E_ALL
log_errors = On
error_log = /var/log/php/error.log

; 本番環境
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
log_errors = On
error_log = /var/log/php/error.log

; 共通
memory_limit = 256M
max_execution_time = 60
upload_max_filesize = 20M
post_max_size = 20M

エラー出力の制御

// 開発時: 全エラーを表示
error_reporting(E_ALL);
ini_set('display_errors', '1');

// 本番: ログのみ
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', '/var/log/php/app.log');

// カスタムハンドラ
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    error_log("[$errno] $errstr at $errfile:$errline");
    return true;
});

// 例外ハンドラ
set_exception_handler(function (Throwable $e) {
    error_log($e->getMessage() . "\n" . $e->getTraceAsString());
    http_response_code(500);
    echo "Internal Server Error";
});

FAQ

Q: 画面が真っ白で何も表示されない
A: display_errors=Off で Fatal が出ているのに表示されない状態。エラーログ (/var/log/php/error.logstorage/logs/laravel.log) を確認してください。

Q: PHP 7 から 8 に上げたら大量の Warning が出る
A: Undefined variable などが Notice → Warning に昇格しました。?? '' / ?-> で防御的にコーディングし直してください。

Q: 本番でエラーがユーザに見えてしまった
A: display_errors=Off 必須。さらに Web サーバ (Nginx/Apache) 側でカスタムエラーページを設定してください。

編集
Post Share
子ページ
  1. Fatal error: Maximum execution time of 30 seconds exceeded in...
  2. Fatal error: Uncaught Error: Cannot use object of type stdClass as array in ...
  3. Warning: Use of undefined constant ... - assumed '...' (this will throw an Error)
  4. ERROR: Call to undefined method Maatwebsite\Excel\Excel::load()
  5. Maximum execution time of 30 seconds exceeded
  6. Your requirements could not be resolved to an installable set of packages. ... To enable extensions, verify that they are enabled in your .ini files:
  7. could not find driver
  8. the requested PHP extension mbstring is missing from your system.
  9. the requested PHP extension dom is missing from your system.
  10. A non well formed numeric value encountered
  11. Warning: Cannot modify header information - headers already sent by ...
  12. php_network_getaddresses: getaddrinfo failed: Name or service not known
  13. XMLWriter::openUri(): Unable to resolve file path
  14. Object of class stdClass could not be converted to string
  15. Class 'Google_Service_Youtube' not found
同階層のページ
  1. インストール方法
  2. 文法
  3. Composerのインストール
  4. 内部関数
  5. フレームワーク
  6. エラー一覧
  7. 改行出力
  8. printとechoの違い
  9. シングルクォートとダブルクォートの違い
  10. returnとyieldの違い
  11. var_dumpをログ出力
  12. CSV読み込み
  13. 待機・処理の遅延
  14. ログファイルにエラーを出力する方法
  15. エラーログ出力関数
  16. URLパラメータの配列化
  17. empty, is_null. issetの判定比較表
  18. httpステータスコードの付与
  19. バージョンの確認
  20. php.ini
  21. APIを呼び出す方法
  22. 外部ファイルを呼び出す方法
  23. カンマ区切りの文字列を配列に変換
  24. 配列からランダムに値を取り出す方法
  25. Webスクレイピング

最近更新/作成されたページ