PHP String Sanitization

PHP Code Snippets String Sanitization


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.



//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:


Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger