How to validate and sanitize user input with PHP?

Data validation is an integral part of web development, especially while working with forms where the user first enters their personal data and then sends that to the database. Data sent in an invalid format can cause DBMS security problems. Hackers often use SQL injections to insert malicious SQL commands into the database. SQL injections can even destroy the database once inserted. Therefore, to safeguard the database from hackers, it is necessary to sanitize and filter the user entered data before sending it to the database.

Let’s have an example of SQL injection to make the things clear.

Suppose the hackers enter ‘5=5’ in the ‘Username’ input box and then submits the data. The condition ‘5=5’ is always true. Therefore, the SQL command that will be executed after the ‘Submit’ button is pressed will be



SELECT * FROM registration WHERE UserId = 105 OR 1=1;

The above SQL command is error-free, and thus the MySQL server will execute it. But, what if the registration table contains sensitive information like credit card information or passwords. A hacker might get information about all the registered users just by entering ‘5=5’ in the username input box, and then misuse it.

To prevent such instances from happening, validation and sanitization of user data are required:
The filter_var function is used for such a purpose. This function generally takes two parameters. First is the variable that needs to be validated, and second is the type of check we want to do on that variable.

Let’s have a look at some of the types of checks along with their examples:

  1. String Sanitization – FILTER_SANITIZE_STRING: This removes all the HTML tags from a string. This will sanitize the input string, and block any HTML tag from entering into the database.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    $geeks= "<h1>GeeksforGeeks Portal</h1>";
    $newgeeks = filter_var($geeks, FILTER_SANITIZE_STRING);
    echo $newgeeks;
    ?>

    chevron_right

    
    

    Output:

    GeeksforGeeks Portal

    Code Explanation:
    The ‘geeks’ variable in the above example stores the header ‘GeeksforGeeks Portal’. This ‘geeks’ variable is then filtered using the FILTER_SANITIZE_STRING. The filtered string is then stored in the ‘newgeeks’ variable. After echoing, the output comes out to be ‘GeeksforGeeks Portal’. This is because there was no HTML tag in the original string, and thus was nothing to filter.

  2. IP Address Validation – FILTER_VALIDATE_IP: This filter checks whether the IP address is valid or not.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    $ipaddr = "126.0.0.5";
      
    if (!filter_var($ipaddr, FILTER_VALIDATE_IP) === false) {
        echo("Valid IP-address");
    } else {
        echo("Invalid IP-address");
    }
    ?>

    chevron_right

    
    

    Output:

    Valid IP-address

    Code Explanation:
    The IP address stored in the $ipaddr variable is found out to be valid. If ‘126.2.5’ was stored in the $ipaddr variable, then the output will come out to be ‘Invalid IP-address’. This is because it doesn’t follow the protocol designed for IP addresses.

  3. Integer Sanitization – FILTER_VALIDATE_INT: This filter checks whether a variable is an integer or not.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    $num = 500;
      
    if (!filter_var($num, FILTER_VALIDATE_INT) === false) {
        echo("Valid");
    } else {
        echo("Invalid");
    }
    ?>

    chevron_right

    
    

    Output:

    Valid

    Code Explanation:
    The code will output ‘Valid’ if $num is a valid integer, otherwise, the output will be ‘Invalid’. Here, 500 is an integer, and that’s why the output comes out to be ‘Valid’.

  4. Email ID Validation – FILTER_SANITIZE_EMAIL and FILTER_VALIDATE_EMAIL: This filter first removes all the illegal characters from the email and then checks whether the format is valid or not.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    $em = "career@geeksforgeeks.com";
      
    // Removing the illegal characters
    $em = filter_var($em, FILTER_SANITIZE_EMAIL);
      
    //Validating
    if (!filter_var($em, FILTER_VALIDATE_EMAIL) === false) {
        echo("$em is valid");
    } else {
        echo("$em is invalid");
    }
    ?>

    chevron_right

    
    

    Output:

    career@geeksforgeeks.com is valid

    Code Explanation:
    First, the email stored in the $em variable is sanitized to remove any illegal characters like ‘/><)*&^' etc. After sanitizing, the email is validated, to check whether the email entered is in a valid format or not.

  5. URL Validation – FILTER_SANITIZE_URL: Like the email filter, this filter also first removes all the illegal characters from the URL and then checks whether the format is valid or not.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    //url sanitizer
    $url = filter_var($url, FILTER_SANITIZE_URL);
      
    //url validator
    if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
        echo("$url is valid");
    } else {
        echo("$url is invalid");
    }
    ?>

    chevron_right

    
    

    Output:

    https://www.geeksforgeeks.com is valid

    Code Explanation:
    The email stored in the $url variable is first sanitized to remove the illegal characters. After that, the URL is checked to find out whether the URL format is valid or not.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.