In old versions of PHP, user data from forms would automatically be imported as PHP variables. Realising this was dangerous, the PHP team made it optional. Of course, that just meant it was optionally dangerous, and thus not much better! Fortunately, this system (known as register_globals) has been removed entirely in modern versions of PHP – you're likely to see references to it only in very old code bases.

For the sake of history if nothing else, the below text is still being kept so you can see why it caused a problem. But if you're using PHP 5.4 or later, you really ought never to worry about it.

The "security through obscurity" thinking of "if no one knows what variables I use, they will not be able to set them themselves" is not worth risking - never trust user data, particularly when working with a database. For example, consider this query:

UPDATE $table SET ReadCount = ReadCount + 1 WHERE MessageID = $MID;

That is an example query for a mythical messageboard that tracks how many times a message has been read. Each time a message is loaded, that query is executed to increment its "ReadCount" number. The $table and $MID parts would be substituted by PHP to be the name of the messageboard table and the current message ID being viewed.

Now, what would happen if a malicious user passed in $table like this:

mypage.php?table=admin SET Password = 'foo';#

The SQL statement would now look like this:

UPDATE admin SET Password = 'foo';# SET ReadCount = ReadCount + 1 WHERE MessageID = $MID;

As you know, # is an SQL comment, which means that everything after the # is ignored, leaving the query as this:

UPDATE admin SET Password = 'foo';

This malicious visitor just set the password of all administrators to "foo"! The way in from there is a cinch, and soon they have complete control over the web site - this hack is commonly referred to as SQL injection.

You are probably sick of reading this, but I will try to make it the last time: do not trust user data!


Next chapter: Choose your file extension carefully >>

Previous chapter: Programming secure PHP

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.