[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More


Update and Secure Legacy PHP Scripts wih filter_input_array and PDO Prepared Statements

Published on
5,548 Points
Last Modified:
John Kawakami
Wake up and code.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.

I’ve been a real nut for filter_var() for years, and have come up with concise ways to use it, but totally missed this other function, which, at first look, seemed a little too specialized.


I was so wrong. This is a great way to filter inputs.  I figured this out while updating some code because it was throwing a zillion “Notice, index foobar not defined.” in the error logs.

Legacy Superglobal $_GET

That’s what happens when your legacy code looks like this:

$bar = $_GET['bar'];

all over the place, and the index “bar” is not defined.  One way to fix this is with filter input:

$bar = filter_input(INPUT_GET, 'bar', FILTER_SANITIZE_STRING);

filter_input() checks for the existence of the value, first, before returning it.  It returns false if the value is unset.

I'll describe filter_input's sibling, filter_input_array later.

To make your scripts safer, you need to stop using string interpolation and concatenation to write database queries.

Eliminate Legacy String Interpolation in Queries

There’s a certain irony here – few articles explain and advocate using filter_input() because many programmers are now using frameworks like Laravel that come with object-relational mappers, Request and Response objects. These encapsulate the superglobals $_GET and $_POST.  

They also encapsulate the database access, so there’s less need to know about quoting SQL input.

Consequently, there’s going to be a lot of existing legacy code with some “worst practices”.

They should be fixed.

Remember when people wrote code like this:

mysql_query("SELECT * FROM users WHERE pass='$_POST[password]'");

In case you didn’t know, you could easily hack this via a “SQL injection attack.”  Pass the page input with password set to:

' OR ''='

The concatenated string would look like this:

SELECT * FROM users WHERE pass='' OR ''=''

If you didn’t already know this, stop right now and read up about SQL injection attacks.  Just search. There’s a lot of info.  You should not write web apps if you don’t know about SQL injection attacks.

Avoiding the SQL Injection Attack

The quick fix to avoid these injection attacks is to use PHP Data Objects (PDO) prepared statements.

Here’s PDO code:

$db = new PDO ( $dsn, $user, $password, $options ) ;
$sth = $db->prepare("SELECT * FROM users WHERE pass=?");

It’s one extra line, to prepare() then execute(), but this pattern eliminates risks from SQL injection.

The execute method escapes $password correctly, and then inserts into the SQL string, surrounded by quotes.  SQL injection is averted.

filter_input_array Saves Lines of Code

filter_input_array() is even better than filter_input().  This code below shows not only savings in lines of code, but a nice convention to use the output of filter_input_array() directly into PDO prepared statements.

Imagine you have foo, the int, and bar, the string.  You can filter for both at once:

$get = filter_input_array(INPUT_GET, [

Look at that!  You can take all your inputs, and validate them in one place, right at the top of your code.

You should put this code right at the top of any method that uses the input.  If the old code is OO, you can go the next step and separate out sanitizing and loading values into a method.

Then, later, you eliminate all uses of $_GET, replacing it with $get.

$foo = $_GET['foo'];


$foo = $get['foo'];

Or, in OO code:

$foo = $this->get('foo');

Then, further down,  you can fix up the database code with PDO. PDO has a nice feature where you can name parameters, like this:

$sth = $db->prepare("SELECT * FROM users WHERE foo=:foo");

Let’s try this with foo and bar, and we’ll use $get instead of $_GET.

$sth = $db->prepare("INSERT INTO glorp COLUMNS(foo,bar) VALUES(:foo,:bar)");

Well, look at that!

The code isn’t just safer, it’s also shorter. Concatenate the two parts together, and you have:

$get = filter_input_array(INPUT_GET, [
$sth = $db->prepare("INSERT INTO glorp COLUMNS(foo,bar) VALUES(:foo,:bar)");

The db link setup isn’t there, the FILTER_* are not strict enough, and there are no views, but you get the idea.  This is an easy, quick way to take old scripts and make them safer.


Expert Comment

by:Vincenzo Vecchio
Hi many thanks for your post is really interesting, is there any way to do the same with procedural prepared statement? Many thanks

Author Comment

by:John Kawakami
PHP.net has an article about stored procedures and PDO: http://php.net/manual/en/pdo.prepared-statements.php

Featured Post

Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Join & Write a Comment

Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month