Laravel生产环境serve命令崩溃:Undefined array key 1报错求助
Laravel
serve命令偶尔崩溃,报Undefined array key错误 环境信息
- Laravel v10.48
- PHP 8.2.4
- Composer 2.7.1
问题描述
生产环境执行php artisan serve --host XXX.XXX.X.XX --port XX时,服务偶尔崩溃,CMD中出现以下两类报错:
报错1
ErrorException Undefined array key 1 at vendor\laravel\framework\src\Illuminate\Foundation\Console\ServeCommand.php:328 324▕ $line = str_replace(' ', ' ', $line); 325▕ 326▕ preg_match($regex, $line, $matches); 327▕ ➜ 328▕ return Carbon::createFromFormat('D M d H:i:s Y', $matches[1]); 329▕ } 330▕ 331▕ /** 332 | * Get the request port from the given PHP server output. 1 vendor\laravel\framework\src\Illuminate\Foundation\Console\ServeCommand.php:328 Illuminate\Foundation\Bootstrap\HandleExceptions::Illuminate\Foundation\Bootstrap\{closure}("Undefined array key 0", "C:\Users\ict\Desktop\intranet\vendor\laravel\framework\src\Illuminate\Foundation\Console\ServeCommand.php") 2 vendor\laravel\framework\src\Illuminate\Collections\Traits\EnumeratesValues.php:264 Illuminate\Foundation\Console\ServeCommand::getDateFromLine("XX.X.XX:51140 Accepted")
报错2
ErrorException Undefined array key 1 at vendor\laravel\framework\src\Illuminate\Foundation\Console\ServeCommand.php:344 340▕ protected function getRequestPortFromLine($line) 341▕ { 342▕ preg_match('/:(\d+)\s(?:(?:\w+$)|(?:\[.*))/', $line, $matches); 343▕ ➜ 344▕ return (int) $matches[1]; 345▕ } 346▕ 347▕ /** 348▕ * Get the console command options. 1 vendor\laravel\framework\src\Illuminate\Foundation\Console\ServeCommand.php:344 Illuminate\Foundation\Bootstrap\HandleExceptions::Illuminate\Foundation\Bootstrap\{closure}("Undefined array key 1", "C:\Users\ict\Desktop\intranet\vendor\laravel\framework\src\Illuminate\Foundation\Console\ServeCommand.php") 2 vendor\laravel\framework\src\Illuminate\Foundation\Console\ServeCommand.php:272 Illuminate\Foundation\Console\ServeCommand::getRequestPortFromLine(" Closing")
已尝试操作
升级PHP、Laravel版本及更新Composer,问题未解决。
原因分析
两个报错均因PHP内置服务器输出的日志行不符合ServeCommand中预设的正则匹配规则,导致preg_match未捕获到目标内容,直接访问$matches[1]触发数组键不存在的错误:
- 报错1:
getDateFromLine方法处理XX.X.XX:51140 Accepted这类无时间戳的日志行时,正则未匹配到时间字符串 - 报错2:
getRequestPortFromLine方法处理Closing这类无端口信息的日志行时,正则未匹配到端口号
修复方案
临时修复(修改vendor文件)
直接修改vendor/laravel/framework/src/Illuminate/Foundation/Console/ServeCommand.php中的对应方法,添加匹配检查:
- 修复
getDateFromLine方法:
protected function getDateFromLine($line) { $regex = '/^\[(.*)\]/'; $line = str_replace(' ', ' ', $line); preg_match($regex, $line, $matches); if (!isset($matches[1])) { return Carbon::now(); } return Carbon::createFromFormat('D M d H:i:s Y', $matches[1]); }
- 修复
getRequestPortFromLine方法:
protected function getRequestPortFromLine($line) { preg_match('/:(\d+)\s(?:(?:\w+$)|(?:\[.*))/', $line, $matches); return isset($matches[1]) ? (int) $matches[1] : 0; }
长期解决方案
php artisan serve仅为开发环境调试工具,不建议用于生产环境。生产环境应使用Nginx、Apache等专业Web服务器部署Laravel项目,从根源避免此类问题。
内容的提问来源于stack exchange,提问作者Cressi
相关产品推荐
相关产品推荐

