我在我的网站上使用联系表单,我正在尝试使用PHP验证用户输入。它的问题是虽然它会验证输入正常,但如果你输入正确的详细信息并点击发送,它就不会做任何事情。我认为这是因为在输入错误后它没有执行if
语句的第二部分,但我不确定如何解决它。下面是我到目前为止使用的代码。
<?php
error_reporting(E_ALL ^ E_NOTICE);
function fix_string($var)
{
if(get_magic_quotes_gpc()) $var = stripslashes($var);
$var = strip_tags($var);
return $var;
}
{
$details = array('name' => fix_string($_POST['name']),
'email' => fix_string($_POST['email']),
'number' => fix_string($_POST['number']),
'message' => fix_string($_POST['message']));
}
$send = $_POST['send'];
$message = "";
$email = $details['email'];
foreach ($details as $field => $detail)
$message .= ucfirst($field) . ": " . $detail . "\r\n";
$to = "smokey.12345@hotmail.co.uk";
$subject = "Website contact form";
$message = wordwrap($message, 70, "\r\n");
$headers = 'From: ' .$email . "\r\n" .
'Reply-To: ' .$email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
function trim_value(&$value)
{
$value = trim($value);
}
array_walk($details, 'trim_value');
if ($send)
{
foreach ($details as $field => $detail)
{
if (empty($detail) && $field!='number')
echo "<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>";
}
if (!is_numeric($details['number']))
echo "<p class='error'>Please enter a valid telephone number</p>";
}
else
{
mail($to, $subject, $message, $headers);
echo "<p class='success'>Thank you for your message, you will receive a response shortly.</p>";
}
?>
<div id="contactform">
<form action="" method="post">
<fieldset>
<label for="name">Name:<span class="star">*</span></label> <br />
<input type="text" name="name" id="name" placeholder="Enter your name" maxlength="50" required />
<label for="email">Email:<span class="star">*</span></label> <br />
<input type="email" name="email" id="email" placeholder="Enter your email address" maxlength="100" required />
<label for="number">Telephone: </label><input type="tel" name="number" id="number" placeholder="Enter your phone number" maxlength="12" />
<label for="message">Message:<span class="star">*</span></label>
<textarea name="message" id="message" placeholder="Enter your message" cols="54" rows="5" required></textarea>
<p class="small"><span class="star">*</span> Denotes a required field </p>
<input type="submit" id="send" name="send" value="Send" />
</fieldset>
</form>
我尝试将其更改为while
循环,只是进行验证直到它有效,然后发送电子邮件,但我对此的尝试也不起作用。
答案 0 :(得分:1)
您可以尝试将if($ send){}块更改为以下内容并进行测试吗?
if ($send) {
$bHasError = false;
foreach ($details as $field => $detail) {
if (empty($detail) && $field!='number') {
echo "<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>";
$bHasError = true;
}
}
if (!is_numeric($details['number'])) {
echo "<p class='error'>Please enter a valid telephone number</p>";
$bHasError = true;
}
if (!$bHasError) {
mail($to, $subject, $message, $headers);
echo "<p class='success'>Thank you for your message, you will receive a response shortly.</p>";
}
}