求助:PHP文件直接显示代码且服务器返回405 Not Allowed错误
问题解决指南
一、本地打开PHP文件直接显示代码的解决
本地浏览器直接打开.php文件时,只会将其当作普通文本解析,因为缺少PHP运行环境支撑。解决方法:
- 搭建本地PHP环境(如XAMPP、WAMP),将HTML和PHP文件放到环境的网站根目录(比如XAMPP的
htdocs文件夹) - 通过
localhost/文件名.php的方式访问页面,而非直接双击打开文件
二、Nginx返回405 Not Allowed的解决
这个错误是Nginx未正确处理PHP请求或权限配置导致的,按以下步骤排查:
- 检查Nginx配置文件,确保server块中包含PHP请求处理规则,替换为你的网站根目录:
location ~ \.php$ { root /你的网站根目录路径; fastcgi_pass 127.0.0.1:9000; # PHP-FPM默认端口,根据实际版本调整 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }
- 重启Nginx和PHP-FPM服务:
sudo systemctl restart nginx sudo systemctl restart php-fpm # 若为特定版本,如php7.4-fpm,需对应修改
- 调整文件权限,确保服务器用户(如
www-data)能读写相关文件:
sudo chown www-data:www-data survey.php emails.txt sudo chmod 644 survey.php sudo chmod 666 emails.txt # 写入文件需要可写权限
三、代码错误修正
HTML代码问题
输入框缺少name属性,PHP无法通过$_POST["emails"]获取值,修改后:
<form action="survey.php" method="post"> Your E-mail address: <input type="text" id="emails" name="emails" placeholder="Enter your E-mail address"><br /> <input type="submit" value="提交"> </form>
PHP代码问题
- PHP字符串拼接使用
.而非+,+是数字运算符,会导致字符串被强制转成数字计算 - 重复打开文件的逻辑冗余,优化后代码:
<?php $file_emails = "emails.txt"; // 获取已有记录行数 $line_count = file_exists($file_emails) ? count(file($file_emails)) : 0; // 拼接要写入的内容 $content = "Respondent " . ($line_count + 1) . ":" . $_POST["emails"] . "\n"; // 写入文件 file_put_contents($file_emails, $content, FILE_APPEND) or die("写入文件失败!"); // 可选:提交后跳转至感谢页 header("Location: thankyou.html"); exit; ?>
内容的提问来源于stack exchange,提问作者Kewuaipao
相关产品推荐
相关产品推荐

