PHP表单提交触发服务器端错误,请求代码问题排查与解决
解决PHP邮件发送代码的服务器端错误
嘿,我来帮你一步步搞定这些邮件发送的问题!结合你的代码和错误日志,咱们逐个击破:
1. 语法错误(Unexpected ''X-Mailer'')
这个错误出现在构建$headers的第16行,大概率是字符串拼接时的小失误——要么是漏了拼接操作符(.),要么是换行符的写法有问题。正确的写法要确保每个字符串段都用.连接,换行符\r\n被正确包裹在引号里。
修正后的$headers建议改成这样(顺便优化了回复地址,用用户提交的邮箱更实用):
$headers = 'From: getintouch@reproductivehealthservices.com' . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
2. mail()参数错误(Expected string, array given)
这个错误说明你传给mail()的第四个参数(也就是$headers)变成了数组,但原生mail()函数要求这个参数是字符串。应该是你修改代码时不小心把$headers定义成了数组(比如写成$headers = [];),只要确保$headers是上面那样拼接的字符串,这个问题就会消失。
3. 无法修改Header信息(Headers already sent)
错误日志提到“headers already sent by (output started at ... line23)”,line23就是你输出的<script>标签。HTTP头必须在任何页面输出(包括HTML标签、空格、换行)之前发送,如果你已经输出了script内容,再用header()跳转就会报错。
解决方法二选一:
- 保持现有前端跳转:就用你写的
window.location.replace,没问题,但要确保代码里没有额外的header('Location: ...')语句; - 改用后端跳转:删除所有输出(包括script、空格),直接用
header():
// 发送邮件后直接跳转,注意要放在所有输出之前 mail($to, $subject, $message, $headers); header('Location: ../get-in-touch/index.html'); exit; // 一定要加exit,防止后续代码继续执行
额外安全提醒(新手必看!)
作为PHP新手,还要注意表单提交的安全问题,避免恶意输入:
- 验证邮箱格式:用
filter_var()确保用户输入的是有效邮箱:
$email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL); if (!$email) { header('Location: ../get-in-touch/index.html?error=invalid-email'); exit; }
- 过滤所有输入内容:防止邮件头注入攻击(比如有人在姓名里插入恶意邮件头),可以写个简单的过滤函数:
function sanitize_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } $name = sanitize_input($_POST['name']); $comment = sanitize_input($_POST['comment']);
完整修正后的代码
把所有修正整合起来,最终代码如下(还帮你改了几个拼写小错误):
<?php // 安全过滤输入的辅助函数 function sanitize_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } // 处理并过滤所有表单参数 $name = sanitize_input($_POST['name']); $email = filter_var(sanitize_input($_POST['email']), FILTER_VALIDATE_EMAIL); $number = sanitize_input($_POST['number']); $enquiry = sanitize_input($_POST['enquiry']); $reaction = sanitize_input($_POST['reaction']); $cpreference = sanitize_input($_POST['cpreference']); $comment = sanitize_input($_POST['comment']); // 验证邮箱有效性,无效则跳转回表单提示 if (!$email) { header('Location: ../get-in-touch/index.html?error=invalid-email'); exit; } $to = 'reproductivehealthservices@gmail.com'; // 修正了拼写错误:repoductive → reproductive $subject = 'New Get-In-Touch Form Received'; // 修正拼写:Recieved → Received $message = "Name: ".$name."\n". "Email: ".$email."\n". "Phone Number: ".$number."\n". "Type of Enquiry: ".$enquiry."\n". "Contact Back: ".$reaction."\n". "Contact Preference: ".$cpreference."\n". "Comments: ".$comment; $headers = 'From: getintouch@reproductivehealthservices.com' . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion(); // 执行邮件发送 mail($to, $subject, $message, $headers); ?> <script> alert('Thanks! We will get back to you soon.'); window.location.replace("../get-in-touch/index.html"); </script>
内容的提问来源于stack exchange,提问作者user6874627
相关产品推荐
相关产品推荐

