当我试图自定义使用PHP表单发送的内容的布局时,PHP的语法遇到了困难。我试图在电子邮件的不同行上显示每个输入。。。下面是我的PHP代码:
<?php
// Section 1.
if( $_POST['name_here_goes'] == '' ){
// Section 2.
if ( !empty($_POST['firstName']) && !empty($_POST['lastName']) && !empty($_POST['emailAddress']) ) {
$to = '####@############.com';
$subject = 'NEW Contact Form';
$message = $_POST['firstName'] "'n'n" $_POST['lastName'];
$headers = 'From: ' . $_POST['emailAddress'] . ' ' . "'r'n" .
'Reply-To: ' . $_POST['emailAddress'] . '' . "'r'n" .
'X-Mailer: PHP/' . phpversion();
// Section 3.
if ( mail($to, $subject, $message, $headers) ) {
echo 'Email sent. Congrats!';
}
}else{
echo 'Please fill all the info.';
}
}else{
// Section 4.
echo 'Spam detected!';
}
这是我的HTML代码:
<form name="contact" method="post" action="sell.php">
<div>
<input type="text" name="firstName" value="" placeholder="First Name" />
<input type="text" name="lastName" value="" placeholder="Last Name" />
<input type="text" name="emailAddress" value="" placeholder="Email" />
</div>
<div>
<input type="text" class="robotic" name="name_here_goes" value="" />
<input type="submit" name="submit" value="Submit"/>
</div>
</form>
您可以看到这一行:
$message = $_POST['firstName'] "'n'n" $_POST['lastName'];
它缺少POST阵列之间的连接,并且将错误报告设置为捕获和显示,这会让你:
分析错误:语法错误,第x行上/path/to/file.php中出现意外的"''n''n"(T_CONSTANT_ENCAPSED_STRING)
更改为:
$message = $_POST['firstName'] . "'n'n" . $_POST['lastName'];
^ ^ added
然而,您需要处理一些头,并且不应该像那样直接传递POST数组,您可能会受到XSS注入的影响。
参考文献:
- http://php.net/manual/en/function.error-reporting.php
- http://php.net/manual/en/function.mail.php
- 如何用HTML/PHP防止XSS
将错误报告添加到文件顶部,这将有助于查找错误。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
旁注:显示错误只能在暂存中进行,而不能在生产中进行。
此外,如评论中所述。PHPmailer/Swiftmailer已经为您设置好了,可以很好地使用和处理纯文本和HTML格式的邮件。
- https://github.com/PHPMailer/PHPMailer
- http://swiftmailer.org/
编辑:
"很抱歉延迟了响应……成功了!但你如何在提交后将其直接指向另一个页面?–Nick"
你会使用一个标题http://php.net/manual/en/function.header.php并且将echo 'Email sent. Congrats!';
替换为标头,则不能同时使用两者。
if ( mail($to, $subject, $message, $headers) ) {
header('Location: http://www.example.com/');
exit;
}
手册示例:
header('Location: http://www.example.com/');
exit;
请确保您没有在页眉之前输出。如果您确实收到通知,请咨询:
- 如何修复";标头已发送";PHP中的错误
您还可以参考以下内容了解更多重定向方法:
- 如何在PHP中进行重定向