你好PHP和网络爱好者, 在制作简单的电子邮件页面时,我的php代码出现问题。 我得到的错误是语法错误,意外''(T_ENCAPSED_AND_WHITESPACE),期望第19行的标识符。 这是我的代码。我一直试图修复它好几天。
<html>
<h1> Contact Form </h1>
<form action ="HW2-4.php?action=send"method="POST">
<p> Name: <input type="text" name="name" /></p>
<p>Email: <input type="text" name="email" /></p>
<p>Subject: <input type="text" name="subject" /></p>
<p>Message: <textarea col="20" row="5" name="message" ></textarea></p>
<input type="submit" value="Send Email"/>
<?php
if(isset($_POST['action']) and $_POST['action'] == "send"){
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$headers = $_POST["headers"];
if (mail($email, $subject, $message, $headers) == 1) {
echo "<h3>Hello ".$_POST['name']." An email has been sent to you at ".$_POST['email']."!</h3>";
}
}
页面加载,但发送电子邮件后我不会显示echo语句,我不认为该电子邮件正在发送。
答案 0 :(得分:4)
这是因为$_POST['name']
和$_POST['email']
变量未正确解析。您应该将它们连接起来,这本身就是我将变量注入字符串的方式(尽管还有其他选择),即:
echo "<h3>Hello ".$_POST['name']." An email has been sent to you at ".$_POST['email']."!</h3>";
事实上,只需简单地使用双引号:
echo '<h3>Hello '.$_POST['name'].' An email has been sent to you at '.$_POST['email'].'!</h3>';
您还可以查看various ways如何解析字符串,这意味着这些字符串也有效。关于哪个更好falls within the domain of micro-optimisation,因为与服务器负责的其他操作相比,它们之间的差异可以被认为是微不足道的。
方法1:使用{}
:
echo "<h3>Hello {$_POST['name']} An email has been sent to you at {$_POST['email']}!</h3>";
方法2:或完全放弃使用'
:
echo "<h3>Hello $_POST[name] An email has been sent to you at $_POST[email]!</h3>";
方法3(由@Blowski建议):使用sprintf()
:
sprintf('<h3>Hello %s. An email has been sent to you at %s!</h3>', $_POST['name'], $_POST['email']);
方法4:创建一个变量(在这种情况下你已经拥有它们)
echo "<h3>Hello $name. An email has been sent to you at $email!</h3>"