What is Sanitize/ Sanitization ? Why you should Sanitize your Code

What is Sanitize /Sanitization?

Sanitize: If you google, this word or simply look into the dictionary it will show the following result

As shown, Sanitize, generally means: “make clean and hygienic; disinfect.”  Similarly in Computer Science, this term means the removal of malicious data from user input, such as form submissions or maybe more simply, The cleaning of user input to avoid code-conflicts (duplicate ids for instance), security issues (XSS codes etc), or other issues that might arise from non-standardized input & human error/deviance

Depending on the context, sanitization will take on a few different forms. Could be as simple as removing vulgarities & odd symbols from text to removing SQL injection attempts and other malicious code intrusion attempts.

How to Sanitize your Code

:
Every language has its own sets of filters to Sanitize the Code, you can use these filters, to filter out the malicious data or prevent any intrusion attempts

Via this article, we gonna show a simple Code Sanitization using PHP’s filter_input() and filter_var() functions.

   <?php $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); ?>

Above code runs the $_POST element “name” through FILTER_SANITIZE_STRING… which “Strip tags, optionally strip or encode special characters.” You can see a full list of available filters here

 <?php $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); ?>

Which will: “Validates whether the value is a valid e-mail address.” If it’s not a valid email address, filter_var() returns false meaning you can run validations checks off it, like this:

 <?php
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

if ( $email === false ) {
// Handle invalid emails here
}
?>

or you can use filter_input() like this:

<?php
$name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING);
$email= filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$search = filter_input(INPUT_GET, "s", FILTER_SANITIZE_STRING);
?>

This type of simple sanitization will add an extra layer of security and ensure the user input you accept into your application isn’t going to let a hacker into your app.

Why you should Sanitize your Code

Well by using Sanitization filter, you not only make your code clean but it will also Prevent any type of Code injection attempts.

What is Sanitize/ Sanitization ? Why you should Sanitize your Code
You may Also Like
Scroll to top