PHP String Sanitization

PHP Code Snippets String Sanitization
Share:

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

Resulting output:

Share:

Leave a Reply

Your email address will not be published.

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