How to Secure Inputs in PHP

Published on Oct 11, 2020

In this article, we’re going to learn how to sanitize inputs in PHP. It increases the security of the code. Let’s have a look.

Table of Contents

  1. Create Methods
  2. Usage

Create Methods

We’re going to create two functions. One function is clean. It’ll be used for stripping out malicious bits.

function clean($input) {
    $search = array(
      '@<script[^>]*?>.*?</script>@si',   // Javascript tag
      '@<[\/\!]*?[^<>]*?>@si',            // HTML tags
      '@<style[^>]*?>.*?</style>@siU',    // Style tags
      '@<![\s\S]*?--[ \t\n\r]*>@'         // Multi-line
    );

    $output = preg_replace($search, '', $input);
    return $output;
}

We need to create another function named sanitize. Sanitizing usually refers to input, so you are stripping away parts of the input that could be problematic for your program (or avoid SQL injection ).

function sanitize($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
        }
    }
    else {
        if (get_magic_quotes_gpc()) {
            $input = stripslashes($input);
        }
        $input  = cleanInput($input);
        $output = mysql_real_escape_string($input);
    }
    return $output;
}

Usage

Let’s see an example:

$string = "Hello <script>alert('hacked');</script> world!";
$sanitized = sanitize($string);

echo $sanitized; // Hello world!

We can sanitize POST, GET, REQUEST inputs:

$post_data = sanitize($_POST);
$get_data  = sanitize($_GET);
$request_data  = sanitize($_REQUEST);
The tutorial is over. Thanks for reading. ?