Windows下运行PHP开发服务器遇404文件未找到问题求助
我在Windows系统上运行PHP时出现「No such file or directory」错误,站内没找到完全匹配的解决方案。
我通过cmd执行命令:
php -S localhost:4000
访问localhost:4000/www/site.php时提示文件未找到,但我已多次确认路径正确。该服务昨日正常运行,我没做任何更改,现在无法正常工作。
文件实际路径:C:\Users\Spencer\www\site.php
环境变量信息:$_ENV['USERPROFILE'] => C:\Users\Spencer
服务器输出日志:
[Mon Aug 8 17:55:38 2022] PHP 8.1.9 Development Server (http://localhost:4000) started
[Mon Aug 8 17:59:59 2022] [::1]:62146 Accepted
[Mon Aug 8 17:59:59 2022] [::1]:62146 [404]: GET /www/site.php - No such file or directory
[Mon Aug 8 17:59:59 2022] [::1]:62146 Closing
问题出在PHP内置服务器的根目录逻辑上:你执行php -S命令时所在的当前工作目录就是服务器的根目录。现在访问/www/site.php,服务器会在启动命令的目录下查找www/site.php,但你的文件实际在C:\Users\Spencer\www\site.php,说明你今天启动服务器时的目录不是C:\Users\Spencer。
给你两种解决办法:
方法一:切换到正确目录再启动服务器
- 在cmd里执行:
cd C:\Users\Spencer - 再执行:
php -S localhost:4000
之后访问localhost:4000/www/site.php就能正常找到文件。
- 在cmd里执行:
方法二:启动时直接指定根目录
不管当前cmd在哪个目录,直接执行这条命令:php -S localhost:4000 -t C:\Users\Spencer-t参数用来指定PHP内置服务器的根目录,这样服务器会以C:\Users\Spencer为根目录,自然能找到www/site.php。
昨天正常今天失效的原因,大概率是你昨天启动cmd时默认目录是C:\Users\Spencer,今天打开cmd时默认目录发生了变化(比如系统默认打开到C:\Windows\System32或个人文档文件夹),导致服务器根目录不匹配。
内容的提问来源于stack exchange,提问作者EnderPrince

