需要将一个数组转移到另一个php错误数组,以便两个php文件一起工作,以便表单可以工作。
更新
PHP的新手! 尝试用html表单处理PHP邮件,但是以某种方式当我提交空表单时,它并没有捕获我的if语句错误,而只是直接联系contactform.php一个空白页面,而不是显示错误的主索引页面。
index.php和contactform.php都是单独的文件。
<?php
//setting error empty string
$errors = ['empty' , 'name', 'subject', 'mail', 'message'];
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$message = $_POST['message'];
if(empty($name) or empty($subject) or empty($mailFrom) or empty($message))
{
$errors['empty']="Please fill the empty form";
}
if( !preg_match ("/^[a-zA-Z\s]+$/",$name)) {
$errors['name'] = "Name must only contain letters!";
}
if( !preg_match ("/^[a-zA-Z\s]+$/",$subject)) {
$errors['subject'] = "Subject must only contain letters!";
}
if(!filter_var($mailFrom, FILTER_VALIDATE_EMAIL)) {
$errors['mail'] = "Invalid email format";
}
if( !preg_match ("/[A-Za-z0-9]+/",$message)){
$errors['message'] = "Your message must not contain special characters";
}
$mailTo = "my@email.com";
$headers = "From: ". $mailFrom;
$txt = "You have received an e-mail from" .".\n\n".$name.".\n\n".$message;
if(!isset($errors) || count($errors) == 0) {
mail($mailTo, $subject, $txt, $headers);
header("Location: index.php");
}
}
?>
HTML文件
<form class="box" action="contactform.php" method="post">
<div class="container-text">
<p>
<label>Name</label>
<input type="text" name="name" placeholder="Full Name">
<span class="error">* <?php echo isset($errors['name']) ?
$errors['name'] : "";?></span>
</p>
<p>
<label>Subject</label>
<input type="text" name="subject" placeholder="Subject">
<span class="error">* <?php echo isset ($errors['subject']) ?
$errors['subject'] : "";?></span>
</p>
<p>
<label>Email</label>
<input type="text" name="mail" placeholder="Your e-mail">
<span class="error">* <?php echo isset ($errors['mail']) ?
$errors['mail'] : "";?></span>
</p>
<p>
<label>Message</label>
<textarea name="message" row="5" placeholder="Message">
</textarea>
<span class="error">* <?php echo isset ($errors['message']) ?
$errors['message'] : "";s?></span>
</p>
</div>
<div class="full-container">
<p>
<button type="submit" name="submit" value="submit"
>Submit</button>
</p>
</div>
</div>
</form>
答案 0 :(得分:0)
您分配了error_empty
和其他错误,但是在调用mail()
和header()
之前,您无需检查其中是否有错误。
最简单的解决方法:将它们放入数组$errors['empty'] = "message"
中并检查count($errors)
,或者设置标志$hasError
并进行检查。
以下是我的拳头建议的简短示例实现:
//...
if(empty($name) or empty($subject) or empty($mailFrom) or empty($message)){
$errors['empty'] = "Please fill the empty form";
}
if( !preg_match ("/^[a-zA-Z\s]+$/",$name)) {
$errors['name'] = "Name must only contain letters!";
}
//... repeat for other values and do other stuff
if(!isset($errors) || count($errors) == 0) {
mail($mailTo, $subject, $txt, $headers);
header("Location: index.php?mailsent");
}
// now you can show the error like so:
?>
<input type="text" name="name" placeholder="Full Name">
<span class="error">* <?php echo isset($errors['name']) ? $errors['name'] : ""; ?></span></p>