• How to Validate Form with PHP – Server Side Validation

    In this post, you’ll learn – How to Validate Forms with PHP and it will be a server side form validation. We will create a user registration form at first, and then we will validate fields of that form such as name, email, phone number, birth date, bio etc.
    How to Validate Form with PHP - Server Side Validation hi res snap

    What is the difference between client side form validation and server side form validation?

    Client side form validation is done in user’s machine but server side form validation is done on server. We cannot relay on data that are only validated in client side because a expert level user may change those data before submission to the server. Bad data can harm a server, steal information or even can delete a whole database.
    As server side form validation is done on server, the submitted data is validated and cleaned by server and then it is used. No one can modify those data without having access to the server.

    Validate a HTML Form with PHP

    In this example, you will need two files as below with correspondence names. Save these files and try in your local machine. These files are commented enough to understand what’s going on.

    html_form_to_validate.php

    Form has been submitted successfully."; // showing success message // hashing the password and sanitize data $_POST['password'] = md5($_POST['password']); foreach ($_POST as $key => $val) { $_POST[$key] = mysql_real_escape_string($_POST[$key]); // Or you can use $mysqli->real_escape_string() as above function is deprecated // Or you can use prepared statements to sanitize // Use stripslashes to do the opposite } // do stuffs with validated & safe data //show the raw data (for practice) var_dump($_POST); } ?>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    <?php
    include('validate.php');
    function selected($blood_group, $choice) {
    if($blood_group==$choice) echo "selected";
    }
    ?>
    <html>
    <head>
    <title>Validating Form with PHP - by Arpan Das (http://w3epic.net)</title>
    <style>
    body {
    font-family: 'trebuchet ms';
    font-size: 1.4em;
    padding: 0 50px; color: #444;
    }
    input, textarea {font-size: 1em;}
    p.error {background: #ffd; color: red;}
    p.error:before {content: "Error: ";}
    p.success {background: #ffd; color: green;}
    p.success:before {content: "Success: ";}
    p.error, p.success {font-weight: bold;}
    </style>
    </head>
    <body>
    <h1>Validating Form with PHP - by Arpan Das (http://w3epic.net)</h1>
    <h2>Please fill up the form below and submit.</h2>
    <?=$error?>
    <form action="html_form_to_validate.php" method="post">
    <table>
    <tr>
    <td>Username: </td>
    <td><input type="text" name="username" value="<?=@$username?>"/> (3 to 20 alpha-numeric characters)</td>
    </tr>
    <tr>
    <td>First name: </td>
    <td><input type="text" name="first_name" value="<?=@$first_name?>"/> (3 to 20 alpha characters only)</td>
    </tr>
    <tr>
    <td>Last name: </td>
    <td><input type="text" name="last_name" value="<?=@$last_name?>"/> (3 to 20 alpha characters only)</td>
    </tr>
    <tr>
    <td>Password: </td>
    <td><input type="password" name="password" value="<?=@$password?>"/> (3 to 20 characters only)</td>
    </tr>
    <tr>
    <td>Confirm password: </td>
    <td><input type="password" name="confirm_password" value="<?=@$confirm_password?>"/> (3 to 20 characters only)</td>
    </tr>
    <tr>
    <td>Email: </td>
    <td><input type="text" name="email" value="<?=@$email?>"/> (Valid email like name@domain.com)</td>
    </tr>
    <tr>
    <td>Phone: </td>
    <td><input type="text" name="phone" value="<?=@$phone?>"/> (10 digit mobile number)</td>
    </tr>
    <tr>
    <td>Gender: </td>
    <td><input type="radio" name="gender" value="male" <?php if(@$gender=='male')echo 'checked="true"';?>
    <?php if(!isset($gender))echo 'checked="true"';?>/> male
    <input type="radio" name="gender" value="female"
    <?php if(@$gender=='female')echo 'checked="true"';?> /> female</td>
    </tr>
    <tr>
    <td>Blood Group: </td>
    <td>
    <select name='blood_group'>
    <option value="0" >Select Blood Group</option>
    <option value="1" <?php selected(@$blood_group, 1) ?>>A Positive</option>
    <option value="2" <?php selected(@$blood_group, 2) ?>>A Negative</option>
    <option value="3" <?php selected(@$blood_group, 3) ?>>B Positive</option>
    <option value="4" <?php selected(@$blood_group, 4) ?>>B Negative</option>
    <option value="5" <?php selected(@$blood_group, 5) ?>>AB Positive</option>
    <option value="6" <?php selected(@$blood_group, 6) ?>>AB Negative</option>
    <option value="7" <?php selected(@$blood_group, 7) ?>>O Positive</option>
    <option value="8" <?php selected(@$blood_group, 8) ?>>O Negative</option>
    </select>
    </td>
    </tr>
    <tr>
    <td>Date of Birth: </td>
    <td><input type="number" name="day" value="<?=@$day?>" size=2/>/
    <input type="number" name="month" value="<?=@$month?>" size=2/>/
    <input type="number" name="year" value="<?=@$year?>" size=4/> (DD/MM/YYYY)</td>
    </tr>
    <tr>
    <td>Bio: </td>
    <td><textarea name="bio"><?=@$bio?></textarea></td>
    </tr>
    </table>
    <input type="submit" name="submit" value="Submit"/> <input type="reset" name="reset" value="Reset"/>
    </form>
    <?php
    if (isset($_POST['submit']) && $error == '') { // if there is no error, then process further
    echo "<p class='success'>Form has been submitted successfully.</p>"; // showing success message
     
    // hashing the password and sanitize data
    $_POST['password'] = md5($_POST['password']);
    foreach ($_POST as $key => $val) {
    $_POST[$key] = mysql_real_escape_string($_POST[$key]);
    // Or you can use $mysqli->real_escape_string() as above function is deprecated
    // Or you can use prepared statements to sanitize
    // Use stripslashes to do the opposite
    }
     
    // do stuffs with validated & safe data
     
    //show the raw data (for practice)
    var_dump($_POST);
    }
    ?>
    </body>
    </html>

    validate.php

    Explanation

    html_form_to_validate.php

    The core structure – representation part is placed within html_form_to_validate.php and the actual validation process is done in validate.php. We included validate.php in the beginning of html_form_to_validate.php.
    In this form, we used post method. If you want, you can use get method, just change method=”get” and replace $_POST with $_GET – that’s all. We used text inputs, password inputs, number inputs, radio button inputs and a textarea input.
    For each one’s value attribute, we used <?=@$username?>. This PHP syntax is shorthand for echoing a variable inline (see this post for more on PHP Shorthand Syntax) and “@” as prefix on any expression in PHP, any error messages that might be generated by that expression will be ignored. We used “@” in case if the variable is not set, it won’t show any error.
    In the html_form_to_validate.php you can see the input conditions are written at the right side of each input field. Exactly these conditions will be validated in validate.php.
    After all, sanitize is done in line 100. You can  use mysql_real_escape_string() or $mysqli->real_escape_string() or prepared statements. mysql_real_escape_string is deprecated, so I suggest you to use rest of two.

    validate.php

    In validate.php at very beginning, we initialized variable name $error as blank. Then rest of the script will be executed if the form is submitted as line 11. We removed extra white spaces & escaped harmful characters by trim and mysql_real_escape_string functions respectively. Remember, mysql_real_escape_string is deprecated as of PHP 5.5.0, and will be removed in the future versions. So, find an alternative.
    After that, we started to validating each fields from line 30. We used ctype_alnum to check if user input is alpha-numeric or not, If not, we concatenated $error variable by “.=” with a error paragraph telling the error.
    Like that, we also used ctype_alpha and ctype_digit to check alphabets and digits receptively in same way. For the first name and last name field, we used str_replace function to add “-” and “‘” as exception. So, we can put names like Brian O’ConnerGeorges StPierre etc. containing dashes and single quotes.
    To check size of a user input string, we used strlen() function. To validate a range of characters, we used this piece of code
    To check the confirm password is same with password, we just used
    To validate email address, we used filter_var. But you can also use regexp to do the same.
    The rest of it is same. If you need any help on PHP, HTML or CSS – see tutorials below
    You can download the files used in this article from link below
    Need further help? Just leave a comment, I’ll be back to you.
    Thank you!
  • You might also like

    No comments:

    Post a Comment

    Good day precious one, We love you more than anything.

Powered by Blogger.