DEV Community

Cover image for Sanitize Input using PHP
Code And Deploy
Code And Deploy

Posted on

Sanitize Input using PHP

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/sanitize-input-using-php

In this tutorial, we are going the sanitize input in PHP before saving it to our database. This is one of the most important to do when saving records online because we don't know what our visitors think and maybe some of them provide malicious data to our application. For more information please visit sanitize filters at PHP's official website.

So in my previous tutorials, I add a function that will sanitize the input before saving it to our database. Kindly see below sample code.

function sanitize($input) 
{
    if(is_array($input)):
        foreach($input as $key=>$value):
            $result[$key] = sanitize($value);
        endforeach;
    else:
        $result = htmlentities($input, ENT_QUOTES, 'UTF-8');
    endif;

    return $result;
}
Enter fullscreen mode Exit fullscreen mode

As you can see from the above code I create sanitize() function inside the functions.php file. And I have one parameter called $input variable. Then I check if the $input variable is an array if yes then I loop the $input variable value then call the function again with the string value.

So if your $input variable value is not an array then it will call the htmlentities() function to convert the malicious characters to HTML entities. So using this function if your visitor input a script like this:

<script> alert("This is a message"); </script>
Enter fullscreen mode Exit fullscreen mode

Then it will convert the characters into this.

&lt;script&gt;alert( &quot;This is a message&quot; );&lt;/script&gt;
Enter fullscreen mode Exit fullscreen mode

As you can see the script will not read anymore when viewing it because we already converted it into entities.

So next I call the sanitize() function inside my save.php file here is what it looks like.

$request = sanitize($_REQUEST);
Enter fullscreen mode Exit fullscreen mode

So I sanitize the $_REQUEST Super Global variable before saving it to our database.

Here is the complete code of my save.php file.

<?php
    // include config file
    require_once 'config.php';

    //a PHP Super Global variable which used to collect data after submitting it from the form
    // Sanitize fist the values of this variable
    $request = sanitize($_REQUEST);
    //get email address value
    $email = $request['email']; 
    //get first name value
    $first_name = $request['first_name'];
    //get last name value 
    $last_name = $request['last_name'];
    //get address value
    $address = $request['address'];

    // Defined $result as array
    $result = [];

    if(!isEmailValid($email)):
        $result['has_error'] = 1;
        $result['response'] = "Email address is invalid.";
    elseif(isEmailExists($db, "employees", $email)):
        $result['has_error'] = 1;
        $result['response'] = "Email address is already exists.";
    endif;

    // Check if no errors
    if(!count($result)):
        // SQL Statement
        $sql = "INSERT INTO employees (email, first_name, last_name, address)
        VALUES ('".$email."', '".$first_name."', '".$last_name."', '".$address."')";

        // Process the query
        if ($db->query($sql)) {
          $result['response'] = "Employee has been created.";
        } else {
          $result['response'] = "Error: " . $sql . "<br>" . $db->error;
        }

        // Close the connection after using it
        $db->close();
    endif;

    // Encode array into json format
    echo json_encode($result);


?>
Enter fullscreen mode Exit fullscreen mode

Okay, you are now ready and your data is clean before we will process it. So I hope that you have your idea now how important is this and implement it in your projects. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/sanitize-input-using-php if you want to download this code.

Thank you and Happy Coding :)

Discussion (0)