我在使用PHP表单时遇到了一些困难,问题是即使表单字段尚未经过验证,我的确认消息也会显示。
如果表单尚未经过验证,我希望显示另一条消息,向用户解释出现问题并且未发送消息。
不幸的是,我对PHP的理解与我尝试将这个表单放在一起的教程一样好,所以我有点卡住了!有人会善意地向我解释我做错了什么吗?
以下是代码:
<?php
ini_set('display_errors', 'On');
//Defines error variables and sets to empty
$senderErr = $senderEmailErr = $messageErr = "";
//Defines text entry variables and sets to empty
$sender = $senderEmail = $message = "";
//Defines failure/confirmation messages and sets to empty
$thankYou = "";
$formFail = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["sender"])) {
$senderErr = "Name is required";
} else {
$sender = test_input($_POST["sender"]);
// Checks that name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$sender)) {
$senderErr = "Only letters and white space allowed";
}
}
if (empty($_POST["senderEmail"])) {
$senderEmailErr = "Email is required";
} else {
$senderEmail = test_input($_POST["senderEmail"]);
// Checks if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$senderEmail)) {
$senderEmailErr = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$messageErr = "You haven't written anything";
} else {
$message = test_input($_POST["message"]);
}
if($_POST["submit"]) {
$recipient="me@email.com";
$subject="enquiry";
$sender=$_POST["sender"];
$senderEmail=$_POST["senderEmail"];
$message=$_POST["message"];
$mailBody="Name: $sender\nEmail: $senderEmail\n\n$message";
mail($recipient, $subject, $mailBody, "From: $sender <$senderEmail>");
$thankYou = "Thanks for your message. We'll get back to you shortly";
}
else {
$formFail = "Oops. Something went wrong. Please fill out the required fields.";
}
}
?>
我认为这与我没有为失败设定正确条件这一事实有关。问题是,我不太清楚从哪里开始。抱歉成为一个菜鸟。帮助赞赏。感谢。
编辑 - 这是HTML回应Fred关于元素是否被命名的问题:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Name:</label></br>
<input type="text" name="sender"></br>
<span class="error">* <?php echo $senderErr;?></span>
</br>
<label>Email address:</label></br>
<input type="text" name="senderEmail"></br>
<span class="error">* <?php echo $senderEmailErr;?></span>
</br>
<label>Message:</label></br>
<textarea rows="5" cols="20" name="message"></textarea></br>
<span class="error">* <?php echo $messageErr;?></span>
<input type="submit" name="submit" value="submit"></br>
</form>
<span><?php echo $thankYou;?></span>
<span><?php echo $formFail;?></span>
答案 0 :(得分:1)
用if($_POST["submit"])
替换if(($_POST["submit"]) && !empty($_POST["sender"]) && !empty($_POST["senderEmail"]) && !empty($_POST["message"]))
将解决问题。
使用PHP的empty()
函数,确保如果某些内容“空”并在条件语句中使用,则在all
条件满足之前不会执行。