Sanitization is the process of cleaning the user input before it is used in the application. This helps other characters or code from being executed. Cleaning user input makes the data more secure to use.
PHP has several built-in functions that help us to sanitize user input. We are exploring these functions with examples.
htmlspecialchars()
This function converts special characters to HTML entities.
Let's see it in action. This function maintains double-quotes and HTML bold tag to remain as HTML entities.
$str = 'Welcome To "PHP Tutorial" by TutorialsPoint';
echo htmlspecialchars($str);
// Output: Welcome To "PHP Tutorial" by TutorialsPoint
strip_tags()
This function removes all the HTML and PHP tags from a string.
This function removes the HTML bold tag from the string.
$str = 'Welcome To "PHP Tutorial" by TutorialsPoint';
echo strip_tags($str);
// Output: Welcome To "PHP Tutorial" by TutorialsPoint
addslashes()
This function adds backslash before single-quote, double-quote, backslash, and NULL.
This function add backslashes before single-quote in the string.
$str = 'Welcome To "PHP Tutorial" by TutorialsPoint';
echo addslashes($str);
// Output: Welcome To \"PHP Tutorial\" by TutorialsPoint
filter_var()
This function does both validation and sanitization of user inputs.
This function sanitize the email address. In the user input email, there was a space in the email which is illegal. This function removes the gap and produce a genuine email address.
$email = 'john [email protected]';
echo filter_var($email, FILTER_SANITIZE_EMAIL);
// Output: [email protected]