php - 调整交钥匙 PHP 表单以在与表单相同的页面上显示错误消息
问题描述
我有一个可操作的网络表单,当前将错误发送到新页面,即下面 PHP 的$myError部分。
你能帮我调整这些代码片段,以便错误显示在同一页面上,最好是在表格的顶部。
我知道这可能会包含会话,但不知道如何修改我现有的代码。
谢谢!!
这是 HTML:
<form method="post" action="contact.php">
<div class="fields">
<div class="field half">
<input type="text" name="name" id="name" placeholder="Name"/>
<label for="name">Your Name</label>
</div>
<div class="field half">
<input type="text" name="email" id="email" placeholder="Email"/>
<label for="email">Your Email</label>
</div>
<div class="field">
<input type="text" name="subject" id="subject" placeholder="Subject"/>
<label for="email">Your Subject</label>
</div>
<div class="field">
<textarea name="message" id="message" rows="3" placeholder="What's on your mind?"></textarea>
<label for="message">Your Message</label>
</div>
</div>
<ul class="actions">
<li><a type="submit" class="button large submit">Send Message</a></li>
</ul>
</form>
这是PHP:
<?php
/* Set e-mail recipient */
$myemail = "me@dom.ain";
/* Check all form inputs using check_input function */
$yourname = check_input($_POST['yourname'], "Enter your name");
$subject = check_input($_POST['subject'], "Write a subject");
$email = check_input($_POST['email']);
$message = check_input($_POST['message'], "Write your message");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$message = "Hello!
Your contact form has been submitted by:
Name: $yourname
E-mail: $email
URL: $website
message:
$message
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
解决方案
推荐阅读
- web-services - 使用 CURL 调用双向 SSL Web 服务
- linux - sed ack 搜索/用字符串替换换行符
- python - AttributeError: 'NoneType' 对象没有属性 'send' discord.py
- vba - 从剪贴板保存图像 MS Access
- c++ - 固定大小的 3D 表
- python - 如何合并 df1 & df2 但只保留 df2 的新行
- javascript - 如何通过 1 次点击而不是 2 次在移动设备上提交联系表单
- python-3.x - 使用python和re获取2个字符串之间的数据
- bash - yq 读取以获取数组元素
- javascript - 使用 if 语句在数字为 15 时进行页面重定向