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

Raj
  • 22,346
  • 14
  • 99
  • 142
IRHM
  • 1,326
  • 11
  • 77
  • 130
  • 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. – Madara's Ghost Sep 02 '12 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 – IRHM Sep 02 '12 at 14:16
  • 1
    There it is :). Please, don't use `mysql_*` functions to write new code. They are no longer maintained and the community has begun [deprecation process](http://goo.gl/KJveJ). See the *[red box](http://goo.gl/GPmFd)*? Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you can't decide which, [this article](http://goo.gl/3gqF9) will help you. If you pick PDO, [here is good tutorial](http://goo.gl/vFWnC). – Madara's Ghost Sep 02 '12 at 17:40
  • Hi @Truth, I really appreciate the link and guidance. I'm now looking at this. Many thanks and kind regards – IRHM Sep 03 '12 at 16:54

3 Answers3

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.

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 1
    Hi @Gordon, thank you very much for sending me this, this is exactly what I was after. Kind regards – IRHM Sep 02 '12 at 14:14
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')");
jspcal
  • 50,847
  • 7
  • 72
  • 76
  • Hi @jspcal, thank you very much for sending this. It's been very useful. Kind regards – IRHM Sep 02 '12 at 14:15
-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);
    }
EbinPaulose
  • 1,129
  • 3
  • 14
  • 26
  • Hi @EbinPaulose, thank you very much for taking the time to reply to my post and for the solution. Kind regards – IRHM Sep 02 '12 at 14:13