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>';
}
}
?>
Try this to check on the calc question:
if(!is_numeric($answerbox) || (int)$answerbox!=15){
$errors[] = "Math answer is not correct.";
}
!is_numeric checks if it's numeric. If not, the message is added to the errors array.
If it's numeric the second condition is checked. (int) casts the variable as integer, so you can check if it's 15 or not.
As for clearing the form: isn't the form automatically cleared when you submit, since you leave/reload the page?
Related
How do you stop an email being sent to you before the form is fully completed. Currently when submit is clicked even though there are validation errors present that have been picked up via the PHP checks that I have in place:
Code:
if (isset($_POST['submitButton'])) {
$fullName = $_POST['fullName'];
$myGender = isset($_POST['myGender']) ? $_POST['myGender'] : '';
$email = $_POST['email'];
$age = $_POST['age'];
$myDate = isset($_POST['myDate']) ? $_POST['myDate'] : '';
$streetNum = $_POST['streetNum'];
$streetName = $_POST['streetName'];
$city = $_POST['city'];
$state = $_POST['state'];
$postCode = $_POST['postCode'];
$movie = $_POST['movie'];
//You need to se the $var
if (empty($fullName))
{
$errorfullName .= 'Please Enter Your Name';
}
if (!ctype_alpha(str_replace(array(" ", "-"), "",$fullName))) {
$errorfullName .= 'Your name should contain alpha characters only.';
}
if (strlen($fullName) < 3 OR strlen($fullName) > 40) {
$errorfullName .= 'First name should be within 3-40 characters long.';
}
/* Check Gender) */
if ($myGender != 'male' && $myGender != 'female') {
$errormyGender .= 'Please select your gender.';
}
/* Check Email */
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$erroremail .= 'Enter a valid email address.';
}
/* Age */
if (intval($age) == '') {
$errorage .= 'Please enter your current age';
}
if (intval($age) < 3 OR intval($age) > 200){
$errorage .= 'Age must be less than 200 years';
}
if(intval($age) == "/^[0-9]$/" ){
$errorage .= 'Must be numeric numbers';
}
/* check date using explode (breaks a string into an array.)if day is not 1-31, throw error*/
if(empty($myDate))
{
$errormyDate.= 'Please enter a current date';
}
$date_arr = explode ("-", $myDate);
$dateSplit = array_slice($date_arr, 0,1);
$dateYear = current($dateSplit);
if($dateYear > date('Y'))
{
$errormyDate .= 'Sorry your not born in the future';
}
/* Check Address House Number if its not numeric, throw error */
if (intval($streetNum) == '') {
$errorstreetNum .= 'Please add street Number';
}
/* Street Name */
if (strlen($streetName) < 3 OR strlen($streetName) > 200) {
$errorstreetName .= 'Street must be filled out and within 200 characters';
}
/*City Name */
if (strlen($city) < 3 OR strlen($city) > 200) {
$errorcity .= 'City must be filled out and within 200 characters';
}
/*State Name */
if (strlen($state) < 3 OR strlen($state) > 200) {
$errorstate .= 'State must be filled out and within 200 characters';
}
/* Check postCode */
if(intval($postCode) == "/^[0-9]$/" ){
$errorpostCode .= 'Post Code must be numeric numbers';
}
/* Check movie selection */
if (trim($movie) === "select") {
$errormovie .= 'Please select a favourite movie';
}
if ($fullName, $myGender, $email, $age, $myDate, $streetNum, $streetName, $city, $state, $postCode, $movie, == " "){
echo '$errorsuccess .= 'Please complete all sections of the form'';
}
else {
$success = "Thank you for submitting your form; We will be in contact soon";
//send mail
$to = "#yahoo.co.nz";
$subject = "Php form data";
$message = "<p>".$fullName."</p><p>".$myGender."</p><p>".$email."</p><p>".$age."</p><p>".$myDate."</p><p>".$streetNum."</p><p>".$streetName."</p><p>".$city."</p><p>".$state."</p><p>".$postCode."</p><p>".$movie."</p>";
$from = "#yahoo.co.nz";
mail($to,$subject,$message);
}
}
The reason being is that you even though you have several validations completed in the above, none of them are later checked to see if they failed/passed, your only sanity check is here:
if ($fullName, $myGender, $email, $age, $myDate, $streetNum, $streetName, $city, $state, $postCode, $movie, == " "){
Which its self is pretty useless all together, by the way.
A simpler way for this would be to first create an array to hold all the errors.
$errors = array();
Then when you do your individual checks, make them a key, for example:
if (empty($fullName))
{
$errors['fullname'] .= 'Please Enter Your Name';
}
And
if (intval($age) == '') {
$errors['age'] .= ' Please enter your current age.';
}
if (intval($age) < 3 OR intval($age) > 200){
$errors['age'] .= ' Age must be less than 200 years.';
}
if(intval($age) == "/^[0-9]$/" ){
$errors['age'] .= ' Must be numeric numbers.';
}
Then later you can do:
if($errors){
echo 'There are errors in the form. Please observe each of the errors and try again.'. PHP_EOL;
foreach($errors as $idx => $error){
echo ucfirst($idx). ': ' .$error;
}
}
Set something like $err to false at the beginning of the code. Set it to true when an error is detected. (Even if it's already true; just setting it is easier than checking.)
Then, you can condition the final result on $err.
It looks like that in order to send the email, you only need to have a value for each of your input fields (from $fullName to $movie).
Where you are validating the form (for example, when you use if (empty($fullName))..., the error that is produced if the form isn't filled out correctly always differs. Unless you have some kind of reason for this, I would just stick to a generic error variable of $formerror.
Then in the final section of your code, where you use if($fullName...$movie == ''), you could change this to if($fullName...$movie === '' AND !empty($formerror)) so that if any errors were picked up during the validating of the form, you would be able to echo $formerror and if not, the email would send.
if($action == "send"){
$_POST['name'] = $name ;
$_POST['email'] = $email ;
$_POST['phone'] = $phone ;
if(!empty($name) || !empty($email) || !empty($phone)){
.....
} else {
$msg = 'All fields required';
}
//whatever I do only shows $msg.
//already tried that too
if(!empty($_POST['name']) || !empty($_POST['email']) || !empty($_POST['phone'])){
....
}
What Im trying to do is a form that email me the data, and I want all fields to be filled so maybe Im writing the if statement the wrong way.
sorry if I didnt explained well before.
Your code reads:
If name is not empty, or email is not empty, or phone is not empty
This means that as long as at least one of them are non-empty, then you're good!
Pretty sure that's not what you meant. You want:
If name is not empty, AND email is not empty, AND phone is not empty
Use && instead of || and it should just work!
I think you're getting confused by all the negatives involved here. I suspect what you're after is:
if (!(empty($name) || empty($email) || empty($phone))) {
...
} else {
$msg = 'All fields required';
}
Which would be better written (in my opinion) as:
if (empty($name) || empty($email) || empty($phone)) {
$msg = 'All fields required';
} else {
...
}
if($name=='' || $email=='' || $phone=='')
{
$msg='All fields required';
}
else
{
..............
}
I'm getting the error in the title of this question. Help me find what's wrong in my contact form:
<?php
//Prefedined Variables
$to = "example#example.com";
$subject = "1";
if($_POST) {
// Collect POST data from form
$name = stripslashes($_POST['name']);
$email = stripslashes($_POST['email']);
$comment = stripslashes($_POST['comment']);
// Define email variables
$message = date('d/m/Y')."\n" . $name . " (" . $email . ") sent the following comment:\n" . $comment;
$headers = 'From: '.$email.'\r\n\'Reply-To: ' . $email . '\r\n\'X-Mailer: PHP/' . phpversion();
//Validate
$header_injections = preg_match("(\r|\n)(to:|from:|cc:|bcc:)", $comment);
if( ! empty($name) && ! empty($email) && ! empty($comment) && ! $header_injections ) {
if( mail($to, $subject, $message, $headers) ) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
?>
It seems the problem is here, but I don't understand whats wrong!
$header_injections = preg_match("(\r|\n)(to:|from:|cc:|bcc:)", $comment);
Try with:
$header_injections = preg_match("#(\r|\n)(to:|from:|cc:|bcc:)#", $comment);
You must provide a valid symbol at the begining and at the end of you regex, in this example is just #, but you can use / or whatever you want.
Take a look at this article: RegEx delimiters.
Try using this:
$header_injections = preg_match('/(\r|\n)(to:|from:|cc:|bcc:)/', $comment);
Also on your IF condition, you should check $header_injections this way:
if( ! empty($name) && ! empty($email) && ! empty($comment) && FALSE !== $header_injections ) {
As the preg_match can return value that can be casted to boolean and skip your validation.
Hey I have this code that sends an email with some data sent by a form:
<?php
if (isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email ($str) {
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if ($_POST['name'] != '' && $_POST['email'] != '' && $_POST['tel'] != '' && valid_email($_POST['email']) == TRUE && strlen($_POST['comment']) > 1) {
$to = preg_replace("([\r\n])", "", $_POST['receiver']);
$from = preg_replace("([\r\n])", "", $_POST['name']);
$subject = 'Online Message';
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) || preg_match($match, $from) || preg_match($match, $message) || preg_match($match, $subject)) {
die("Header injection detected.");
}
$headers = "From: \"".$_POST['name']."\" <".$_POST['email'].">\n";
$headers .= "Reply-to: ".$_POST['email']."\r\n";
if (mail($to, $subject, $message, $headers)) {
echo 1; //SUCCESS
} else {
echo 2; //FAILURE - server failure
}
} else {
echo 3; //FAILURE - not valid email
}
} else {
die("Direct access not allowed!");
}
I want to add the $_POST['tel'] to the $message variable so in the body of the email I can get the message plus the telephone that people type into the form. In the first part of the code I think I made the telephone input obligatory.
I tried doing $message = $_POST['comment'] && $_POST['tel']; but the only thing I recieve is a 1 in the body of the mail that is the first number of the telephone entered.
$message = 'Comment: ' . $_POST['comment'] . ' Tel: ' . $_POST['tel'];
&& means AND (the logical version) so you're actually getting "true".
Use the period, ., to concotenate strings.
$str = 'Hello'.' world'; print $str;
Outputs Hello world
I'm learning PHP and I'm trying to write a simple email script. I have a function (checkEmpty) to check if all the forms are filled in and if the email adress is valid (isEmailValid). I'm not sure how to return true checkEmpty funciton. Here's my code:
When the submit button is clicked:
if (isset($_POST['submit'])) {
//INSERT FORM VALUES INTO AN ARRAY
$field = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' => $_POST['message']);
//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($field);
checkEmpty($name, $email, $message);
function checkEmpty($name, $email, $message) {
global $name_error;
global $mail_error;
global $message_error;
//CHECK IF NAME FIELD IS EMPTY
if (isset($name) === true && empty($name) === true) {
$name_error = "<span class='error_text'>* Please enter your name</span>";
}
//CHECK IF EMAIL IS EMPTY
if (isset($email) === true && empty($email) === true) {
$mail_error = "<span class='error_text'>* Please enter your email address</span>";
//AND IF IT ISN'T EMPTY CHECK IF IT IS A VALID ONE
}
elseif (!isValidEmail($email)) {
$mail_error = "<span class='error_text'> * Please enter a valid email</span>";
}
//CHECK IF MESSAGE IS EMPTY
if (isset($message) === true && empty($message) === true) {
$message_error = "<span class='error_text'>* Please enter your message</span>";
}
}
// This function tests whether the email address is valid
function isValidEmail($email){
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
if (eregi($pattern, $email))
{
return true;
} else
{
return false;
}
}
I know I shouldn't be using globals in the function, I don't know an alternative. The error messages are display beside each form element.
First of all, using global is a sin. You are polluting global namespace, and this is bad idea, except little ad-hoc scripts and legacy code.
Second, you are misusing isset - for two reasons:
a ) in given context you pass variable $name to function, so it is always set
b ) empty checks whether variable is set or not
Third, you should separate validation from generating html.
Fourth, you can use filter_var instead of regular expression to test if mail is valid.
Last, your code could look like that:
<?php
if (isset($_POST['submit'])) {
$fields = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' => $_POST['message']);
//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($fields);
$errors = validateFields($name, $email, $message);
if (!empty($errors)){
# error
foreach ($errors as $error){
print "<p class='error'>$error</p>";
}
} else {
# all ok, do your stuff
} // if
} // if
function validateFields($name, $email, $post){
$errors = array();
if (empty($name)){$errors[] = "Name can't be empty";}
if (empty($email)){$errors[] = "Email can't be empty";}
if (empty($post)){$errors[] = "Post can't be empty";}
if (!empty($email) && !filter_var($email,FILTER_VALIDATE_EMAIL)){$errors[] = "Invalid email";}
if (!empty($post) && strlen($post)<10){$errors[] = "Post too short (minimum 10 characters)";}
# and so on...
return $errors;
}
First of all, you should really re-think your logic as to avoid global variables.
Eitherway, create a variable $success and set it to true in the top of your functions. If any if statement fails, set it to false. Then return $success in the bottom of your function. Example:
function checkExample($txt) {
$success = true;
if (isset($txt) === true && empty($txt) === true) {
$error = "<span class='error_text'>* Please enter your example text</span>";
$success = false;
}
return $success;
}
I'm not sure this is what you want, the way I see it, you want $mail_error, $message_error and $name_error to be accessible from outside the function. If that's the case, what you need is something like this:
function checkEmpty($name, $email, $message) {
$results = false;
//CHECK IF NAME FIELD IS EMPTY
if (isset($name) === true && empty($name) === true) {
$results['name_error'] = "<span class='error_text'>* Please enter your name</span>";
}
//CHECK IF EMAIL IS EMPTY
if (isset($email) === true && empty($email) === true) {
$results['mail_error'] = "<span class='error_text'>* Please enter your email address</span>";
//AND IF IT ISN'T EMPTY CHECK IF IT IS A VALID ONE
}
elseif (!isValidEmail($email)) {
$results['mail_error'] = "<span class='error_text'> * Please enter a valid email</span>";
}
//CHECK IF MESSAGE IS EMPTY
if (isset($message) === true && empty($message) === true) {
$results['message_error'] = "<span class='error_text'>* Please enter your message</span>";
}
return $results;
}
$errors = checkEmpty($name, $email, $message);
now you can test for errors
if($errors){
extract ($errors); // or simply extract variables from array to be used next to form inputs
} else {
// there are no errors, do other thing if needed...
}