Code has been added to clipboard!

PHP Filtering: Add Security and Order to Your Code

Reading time 3 min
Published Aug 8, 2017
Updated Oct 2, 2019

If you fail to apply PHP filtering (sanitizing and validating) to your data correctly, security issues may arise. It is especially important to consider external data which doesn't always come from secure sources.

All the data coming from outside the code should always be validated and sanitized to prevent data insertion and other user-input related security risks. External data also comes from servers and databases.

PHP filtering sanitizes data by getting rid of all illegal characters. Also, it can validate data, checking whether the information is in the right form.

PHP Filtering: Main Tips

  • PHP includes inbuilt filter functionality, allowing to validate or sanitize data you enter through forms or otherwise.
  • This is extremely useful if you want to use special characters as text without triggering code, preventing data insertion.
  • Validating data means determining whether the data is in correct form.
  • Sanitizing data means to remove of any special characters from the data.

Using filter_lists()

To see what the functionality of PHP filters offers, use the filter_lists() function as you can see in the code example below:

Example
<ul>
  <?php 
    foreach (filter_list() as $id => $filter) {      
      echo '<li>' . $filter . ', ' . filter_id($filter) . '</li>';  
    }
  ?>
</ul>

filter_var() Function Explained

A function that validates and sanitizes data is called filter_var(). It takes two variables upon being initialized. First parameter indicates which variable to sanitize. The second specifies the filter that is to be used.

Reasons to Sanitize Data

There are many uses for external input in web applications:

  • User-defined input from forms.
  • Cookie data.
  • Web service data.
  • Server variable data.
  • Results from database queries.

Making Filter Input

Using code examples, we will now explain how PHP filtering can be used on various types of external data. Let's go over them step by step.

Strings and Integers

The example below shows how filter_var() is used to PHP filter sanitize strings:

Example
<?php
  $str = "<h1>Hey!</h1>";
  $newstring = filter_var($str, FILTER_SANITIZE_STRING);
  echo $newstring;
?>

The code example below illustrates how filter_var() is used to check if a variable is an integer, along with displaying messages according to the outcome:

Example
<?php
  $int = 87;
  if (!filter_var($int, FILTER_VALIDATE_INT) ===  false) {    
    echo "This is an integer.";
  } else {    
    echo "This is not an integer. Or at least not a valid one. Read more about that.";
  }
?>

A slight issue might arise here though. If the value equals 0 (even when the variable is an integer), filter_var() will return false. Use this code to work around it:

Example
<?php
  $int = 0;
  if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int, FILTER_VALIDATE_INT) ===  false) {
    echo "This is an integer.";
  } else {
    echo "This is DEFINiTELY not an integer";
  }
?>

IP Addresses, Emails and URLs

Carefully review the code snippet provided. In it, we use filter_var() to check if a variable is a valid IP address. You can see both possible responses in the code. Which one will be displayed, depends on the results of validation:

Example
<?php
  $ip = "127.0.0.1";
  if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {
    echo "Pretty sure that $ip indeed is working, valid IP address.";
  } else {    
    echo "$ip ? Nope. NOT a valid IP address, I can tell you that much.";
  }
?>

In the example below, you can see we use PHP filter_var() to make PHP sanitize form data (remove any illegal symbols from the e-mail field) and validate whether it is a properly formatted e-mail address:

Example
<?php
  $email = "john.doe@example.com";
  // Remove all illegal characters from email
  $email = filter_var($email, FILTER_SANITIZE_EMAIL);
  // Validate e-mail
  if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {    
    echo "$email is working, valid e-mail address you can send letters to.";
  } else {
    echo "$email is DEFINITELY not an e-mail address";
  }
?>

Now, in the next example, PHP filter_var() is again used for both validation and sanitizing, but this time the object is a URL address. Take a look:

Example
<?php
  $url = "https://www.bitdegree.org/learn/";  	
  // Remove all illegal characters from a url
  $url = filter_var($url, FILTER_SANITIZE_URL);
  // Validate url
  if (!filter_var($url, FILTER_VALIDATE_URL) ===  false) {
    echo "$url is TOTALLY legit. Really, it's a valid URL.";
  } elseecho "$url is DEFINITLELY not a valid, working URL";
  }
?>

PHP Filtering: Summary

  • Inbuilt PHP filtering functionalities lets you easily validate and sanitize the data that either you enter or users input.
  • Validating means finding our whether the data in question is in the right format.
  • Sanitizing gets rid of all the special characters the data might contain. By making PHP sanitize form data, you make sure you're only getting the input the intended to.
Tutorial
Introduction
Installation
Syntax
Variable
Superglobals
Data Types
String
Array
Multidimensional Array
Sort Array
Constant
Operators
Cookies
Sessions
DateTime
Error Handling
Exception Handling
File
Write and Create File
File Open, Read and Close
File Upload
Filtering
Redirecting
Advanced Filters
Forms
Form Required Field
Validate Email/URL
Form Validation
Form Action
Function
Prepared Statements
JSON
Calendar
ZIP File
FTP
HTTP Response
DateTime Functions
Error Functions
File Function
Filter
Math Functions
Mail Function
Miscellaneous Functions
Date Format
String Functions
Array Functions
Directory Functions
MySQL Database
MySQL Connection
MySQL Create Database
MySQL Create Table
MySQL Delete Data
MySQL Insert Data
MySQL Get Last Record ID
MySQL Insert Multiple Records
MySQL Select Data
MySQL Limit Data
MySQL Update Data
MySQLi Functions
AJAX and MySQL
AJAX Search
AJAX Poll
RSS Reader
Read XML File in PHP
XML Parser
SimpleXML Parser
SimpleXML: Node and Attribute
Expat XML Parser
DOMDocument
Libxml Functions
SimpleXML Functions
XML Parsing Functions
PHP isset
PHP echo and print
PHP if else and elseif
PHP switch case
PHP include File
PHP while Loop
PHP for and foreach
PHP mail()
PHP explode()
PHP substr()
PHP str_replace()
PHP array_push
PHP count()