Using various tutorials namely here and here I’ve managed to put together the following PHP script which performs server side validation on the form being submitted. (I already have script which is dealing with the ‘client side’ validation.
<?php
//email signup ajax call
if($_GET['action'] == 'signup'){
//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = "error";
$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address) VALUES ('$email')");
if($insertSignup){ //if insert is successful
$status = "success";
$message = "You have been signed up!";
}
else { //if insert fails
$status = "error";
$message = "Ooops, Theres been a technical error!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
What I’m now trying to do is to add another field, in this case ‘name’ which I’d like to also validate.
The problem I’m having is that I’m not sure how to add another field into the above code. Again, I’ve been trying to find an example which I could use to study from, but I haven’t found any that I can use.
I just wondered whether someone could possibly look at this please, and perhaps point me in the right direction.
Many thanks and kind regards
PHP has a Filter extension to validate and sanitize input.
The function you are looking for is
filter_var_array— Gets multiple variables and optionally filters themThere is also
filter_input_arraybut since there is no easy way to unit-test that properly, it is easier to use the above one instead and pass it the superglobals as needed.Example:
Output (demo):
Once you have the input validated and sanitized put some guard clauses for each of the values in the array and return early when they are false:
Note that you want to use either PDO or mysqli instead of ext/mysql.