I've a contact form, and the last field is a math question to be answered from preventing spam emails. what is best way to check if its only a number, no other characters, & answer should be 15. Also ff possible, how make the form clear after its been submitted?
HTML code:
<p id="math">10 + 5 =<input type="text" name="answerbox" id="answerbox" value="<?= isset($_POST['answerbox']) ? $_POST['answerbox'] : '' ?>"/></p>
I've tried using ctype_digit function, but no luck, didn't work.
if(ctype_digit($answerbox != 15) === true){
$errors[] = "Math answer is not correct.";
}
Full php code:
<?php
if(empty($_POST) === false) {
$errors = array();
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
$answerbox = trim($_POST["answerbox"]);
if(empty($name) === true || empty($email) === true || empty($subject) === true || empty($message) === true || empty($answerbox) === true){
$errors[] = '<p class="formerrors">Please fill in all fields.</p>';
} else {
if (strlen($name) > 25) {
$errors[] = 'Your name is too long.';
}
if (ctype_alpha($name) === false) {
$errors[] = "Your name only should be in letters.";
}
if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)){
$errors[] = "Your email address is not valid, please check.";
}
if($answerbox != 15){
$errors[] = "Math answer is not correct.";
}
if(empty($errors) === true) {
$headers = 'From: '.$email. "\r\n" .
'Reply-To: '.$email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail('me@mymail.me',$subject,$message,$headers);
print "<p class='formerrors'>Thank you for your message, I'll get back to you shortly!</p>";
}
}
}
?>
<?php
if (empty($errors) === false){
foreach ($errors as $error) {
echo'<p class="formerrors">', $error, '</p>';
}
}
?>