0

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

4
  • 2
    I'm from mobile, so I don't have my general comment, but mysql_*functions are outdated. Find one of my comments to learn more. Commented Sep 2, 2012 at 13:33
  • Hi @Truth, thank you very much for this. Some of the code has been in use for sometime, but this is something I'll be implementing. Kind regards Commented Sep 2, 2012 at 14:16
  • 1
    Please don't use mysql_* functions in new code. They were removed from PHP 7.0.0 in 2015. Instead, use prepared statements via PDO or MySQLi. See Why shouldn't I use mysql_* functions in PHP? for more information. Commented Sep 2, 2012 at 17:40
  • Hi @Truth, I really appreciate the link and guidance. I'm now looking at this. Many thanks and kind regards Commented Sep 3, 2012 at 16:54

3 Answers 3

4

PHP has a Filter extension to validate and sanitize input.

The function you are looking for is

There is also filter_input_array but 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:

$userInput = array(
    'signup-email' => 'foo at example.com',
    'name' => 'ArthurDent42'
);

$validatedInput = filter_var_array(
    $userInput, 
    array(
        'signup-email' => FILTER_VALIDATE_EMAIL,
        'name' => array(
            'filter' => FILTER_VALIDATE_REGEXP,
            'options' => array(
                'regexp' => "/^[a-z ]{5,10}$/i"
            )
        )
    )
);

var_dump($validatedInput);

Output (demo):

array(2) { 
    ["signup-email"]=> bool(false) 
    ["name"]=> bool(false)
}

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:

if (!$validatedInput['signup-email']) {
    return json_encode(array(
        'status' => 'error',
        'message' => 'The eMail was invalid'
    ));
}

if (!$validatedInput['name']) {
    return json_encode(array(
        'status' => 'error',
        'message' => 'Name must be 5 to 10 letters from A to Z only'
    ));
}

// everything's validated at this point. Insert stuff to database now.

Note that you want to use either PDO or mysqli instead of ext/mysql.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Gordon, thank you very much for sending me this, this is exactly what I was after. Kind regards
0

In your HTML add a field:

<input type="text" name="name" value="" />

In your PHP:

$name = trim($_POST['name']);

To validate:

if ($name === '') {
    $status = 'error';
    $message = 'need a name!';
}

Now add name to your insert statement (it would be better to use PDO prepared statements):

$nameSql = mysql_real_escape_string($name);
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, name) VALUES ('$email', '$nameSql')");

1 Comment

Hi @jspcal, thank you very much for sending this. It's been very useful. Kind regards
-1
    $rule['email']= '/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$`/'
    $rule['name']= 'bla bla';
    $rule['address']= 'bla bla';

   $data =  sanitize($_POST,$rule);
    function sanitize($input_array,$rule){
    $message = array();
     foreach($input_array as $key=> $value){
     $input_array[$key]= mysql_real_escape_string($value);
     if(isset($rule[$key])){
      if(!preg_match($rule[$key],$input_array[$key]){
        $message[$key] = 'error';
        unset($input_array[$key]);//optional
       }
      }
     }
    return array('data'=>$input_array,'message'=>$message);
    }

1 Comment

Hi @EbinPaulose, thank you very much for taking the time to reply to my post and for the solution. Kind regards

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.