About
In this code snippet, we’ll learn how to perform string sanitization in PHP.
An attacker might try to inject some malicious code into your backend. As a developer, you can prevent that by filtering/sanitizing and validating your data before working with it.
Let’s see how to sanitize your strings in the example below.
Code:
<?php //Get unsanitized data from the request. $unsanitizedString = $_GET["value"]; //Filter unsanitized and get a sanitized string. $sanitizedString = filter_var($unsanitizedString, FILTER_SANITIZE_STRING); echo $sanitizedString; //Filters explanation.//////////////////////////// //FILTER_SANITIZE_STRING Sanatizes string. //filter_var($unsanitizedString, FILTER_SANITIZE_STRING); //FILTER_SANITIZE_FULL_SPECIAL_CHAR Sanatizes string but encodes special characters instead of removing them. //filter_var($unsanitizedString, FILTER_SANITIZE_FULL_SPECIAL_CHARS); //FILTER_SANITIZE_EMAIL Sanatizes the string except the email. //filter_var($unsanitizedString, FILTER_SANITIZE_EMAIL); //More filters: https://www.php.net/manual/en/filter.filters.sanitize.php //////////////////////////////////////////////////