【发布时间】:2025-12-24 15:35:12
【问题描述】:
每次我访问该页面时,我的联系表单都会发送黑色电子邮件,并且每当有人填写表单并单击发送时都会发送另一封电子邮件。我正在尝试学习如何验证我的联系表格的数据,并且一整天都没有运气。到目前为止,我对 php 或 javascript 代码知之甚少,但已经从以前编写的代码中尽力而为。
我尝试使用此http://www.inmotionhosting.com/support/edu/website-design/using-php-and-mysql/how-to-create-a-custom-php-contact-form 来帮助编写代码。
有什么想法吗?
<form action="" method="post" style="width:100%;">
Name*<br> <input type="text" name="name" style="width:50%;" ><br/><br/>
Email*<br> <input type="text" name="email" style="width:50%;"> <br/><br/>
Phone*<br> <input type="text" name="phone" style="width:50%"> <br/><br/>
<input name="submitted" type="submit" value="Send" >
<input name="" type="reset" value"Reset">
</form>
<?php
if (isset($_REQUEST['submitted'])) {
// Initialize error array.
$errors = array();
// Check for a name
if (!empty($_REQUEST['name'])) {
$name = $_REQUEST['name'];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";]
if (preg_match($pattern,$name)) {
$name = $_REQUEST['name'];
} else {
$errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';
}
} else {
$errors[] = 'You forgot to enter your name.';
}
//Check for a valid phone number
if (!empty($_REQUEST['phone'])) {
$phone = $_REQUEST['phone'];
$pattern = "/^[0-9\_]{7,20}/";
if (preg_match($pattern,$phone)) {
$phone = $_REQUEST['phone'];
} else {
$errors[] = 'Your phone number can only be numbers.';
}
} else {
$errors[] = 'You forgot to enter your phone number.';
}
//Check for a valid email
if (!filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'The email provided is not valid.';
}
} else {
$email = $_REQUEST['email'];
}
//End of validation
if (empty($errors)) {
$from = "From: " . $_REQUEST['email'];
$to = "myemail@myemail.com";
$subject = "A comment from " . $name . "";
$message = "Message from " . $name . "
Phone: " . $phone . "
Email: " . $_REQUEST['email'] . "";
mail($to,$subject,$message, $from);
}
//Print Errors
if (isset($_REQUEST['submitted'])) {
// Print any error messages.
if (!empty($errors)) {
echo '<hr /><h3 >The following occurred:</h3><ul>';
// Print each error.
foreach ($errors as $msg) {
echo '<li>'. $msg . '</li>';
}
echo '</ul><h3 >Your mail could not be sent due to input errors.</h3><hr />';
} else {
echo '<hr /><h3 align="center" >Your mail was sent. Thank you!</h3><hr /><p>Below is the message that you sent.</p>';
echo "Message from " . $name . "<br />Phone: ".$phone."<br />Email:" . $email;
}
}
//End of errors array
?>
【问题讨论】:
-
空白页表示语法错误。将
ini_set('display_errors', 1);添加到页面顶部或打开错误日志以查看错误 -
if (empty($errors)) {在首页请求中是true。这就是为什么您每次打开页面时都会发送一封电子邮件 -
你的名字和电话模式会让世界上大多数人失望
-
@Dagon:在另一个问题之后-我们更改了名称并搬迁以适应某些站点验证,现在是时候更改电话号码了)
-
@zerkms ,我将进行变性和理发以通过下一个表格。
标签: php html forms email contact