How to Sanitize Input in PHP

Shraddha Paghdar Feb 02, 2024
PHP
  1. HTML Input Sanitization Using htmlentities() in PHP
  2. HTML Input Sanitization Using filter_var() in PHP
  3. SQL Queries Sanitization in PHP
How to Sanitize Input in PHP

User data needs to be stored in the database, but before storing it in the database, we need to be sure that malformed data is not passed; otherwise, it will screw up the DB. This will protect the integrity of data. Users often get confused between sanitization with validation. The sole difference between them is that validation makes sure that data is in the proper format or not, while later makes sure that no illegal character is present in data. In today’s post, we will learn how to sanitize the input data in PHP before passing it to the database(RDBMS/NoSQL).

The most common input that needs to be sanitized is HTML, input via SQL queries, and user profile information.

HTML Input Sanitization Using htmlentities() in PHP

It is an in-built function provided by PHP which converts all the characters into HTML entities. You can also use htmlspecialchars(), the only difference between these two functions is that htmlspecialchars() convert the special characters to HTML entities while htmlentities() converts all characters.

Syntax of htmlentities() in PHP

htmlentities(string $string, $flags, $characterSet, boolean $doubleEncode);

Parameters

  • $string: It is a mandatory parameter, which takes input data on which conversion should be done.
  • $flags: It is an optional parameter that specifies how to handle invalid encoding, quotes, and the used document type. Some of the flags are ENT_COMPAT, ENT_IGNORE, ENT_HTML5, ENT_NOQUOTES, etc.
  • $characterSet: It is an optional parameter that specifies which character-set to use. Some of the character sets are UTF-8, ISO-8859-1, etc.
  • doubleEncode: It is an optional parameter that specifies whether to encode existing HTML entities or not. The default value will be true, which will convert everything.

Return Value

The output of the above function contains a converted string. It will return an empty string if the string parameter contains invalid encoding unless any flags are set like ENT_IGNORE or ENT_SUBSTITUTE.

Example code:

<?php
    $str = '<a href="https://www.google.com">Go to google.com</a>';
    echo htmlentities($str);
?>

Output:

&lt;a href=&quot;https://www.google.com&quot;&gt;Go to google.com&lt;/a&gt;

HTML Input Sanitization Using filter_var() in PHP

It is an in-built function provided by PHP in which validation and sanitization are performed on input data.

Syntax of filter_var() in PHP

filter_var($inputValue, $filterType);

Parameters

  • $inputValue: It is a mandatory parameter, which takes input data on which filter check will be applied.
  • $filterType: It is a mandatory parameter, which specifies what filter check is to be performed on input data. Supported values are:
    • FILTER_VALIDATE_INT: If input data is a valid integer or not.
    • FILTER_SANITIZE_STRING: If input data is a valid string or not and remove all the HTML tags from an input string.
    • FILTER_VALIDATE_IP: If input data is a valid IP address or not.
    • FILTER_SANITIZE_EMAIL: If input data is a valid email address or not. Filter var will remove illegal characters first, and then validation will be performed.

Return Value

Return the filtered value if successfully passed.

Example code:

<?php
    $inputString = "<p>Hello World! Welcome to PHP tutorial</p>";
    $newstr = filter_var($inputString, FILTER_SANITIZE_STRING);
    echo $newstr. "\n";
?>

Output:

Hello World! Welcome to PHP tutorial

SQL Queries Sanitization in PHP

To prevent SQL injection, developers should always use PDO/MySQLi. PDO is a database abstraction layer. PDO sanitizes and embeds external data into a SQL query safely and avoids the type of problems. Before sending data to DB, process the data using filter_var().

Example code:

<?php
    $servername = "hostname";
    $username = "username";
    $password = "password";
    $dbname = "databaseName";
    $lastname = "doe";

    $connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $statement = $connection->prepare("SELECT id, email, firstname, lastname FROM Users WHERE lastname=:lastname");
    $statement->execute(['lastname' => $lastname]);

    $resultOuput = $statement->setFetchMode(PDO::FETCH_ASSOC);
?>
Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn