Sanitize Input using PHP
Tags: javascript, php, mysql
Published: 2022-03-22 05:07:17

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

[![Advanced Laravel SAAS Starter Kit with CRUD Generator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyjyev8tz3r8vi2w3on1.png)](https://1.envato.market/5g5QAn)

[Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!](https://1.envato.market/5g5QAn)

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.

```php
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;
}
```

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:

```js
<script> alert("This is a message"); </script>
```

Then it will convert the characters into this.

```php
&lt;script&gt;alert( &quot;This is a message&quot; );&lt;/script&gt;
```

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.

```php
$request = sanitize($_REQUEST);
```

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
<?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);


?>
```

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.

[![Advanced Laravel SAAS Starter Kit with CRUD Generator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyjyev8tz3r8vi2w3on1.png)](https://1.envato.market/5g5QAn)

[Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!](https://1.envato.market/5g5QAn)

Thank you and Happy Coding :)