Search

Begone pesky magic_quotes

This is the first snippet I usually incorporate into a new site or project.

Why? Because this is the number one thing that breaks a php script on diffrent servers. The reason is that the team behind PHP decided that it would be cool if all user input was filtered so it contained backslashes for all those terrible single-ticks: ‘.

MySql and single-ticks don’t like each other

The single-ticks is a common security flaw in PHP-scripts that communicates with a database. Hackers or even grandma could hack a site and get access to secret data by just inserting the mentioned tick like this is a login input password field:

monkey' OR 'hacked'='hacked

which in the query could became:

SELECT * FROM users WHERE name = 'steve' AND password = 'monkey' OR 'hacked'='hacked';

Not really what anyone would call secure.

So Zend Team put in a config variable that would put backslashes on all user input and the above query would become:

SELECT * FROM users WHERE name = 'steve' AND password = 'monkey\' OR \'hacked\'=\'hacked';

The problem was that they did it configurable into the php.ini so one could never be sure what configuration the server you decided to put your precious script on. And that turned out to be a slight
disaster. Scripts were hard to implement on different servers from time to time.

Strip ‘em all away

So the best solution IMHO is to strip all magic quotes and to it myself with mysql_real_escape_string() where it is proper to do it.

Here’s the little snippet I put in in my config files on new projects:

function strip_magic_quotes( $arr )
{
	foreach ( $arr as $k => $v )
	{
		if ( is_array( $v ) )
			$arr[ $k ] = strip_magic_quotes( $v );
		else
			$arr[ $k ] = stripslashes( $v );
	}
	return $arr;
}
 
if ( get_magic_quotes_gpc() )
{
	if ( !empty ( $_GET ) ) $_GET		= strip_magic_quotes( $_GET );
	if ( !empty ( $_POST ) ) $_POST		= strip_magic_quotes( $_POST );
	if ( !empty ( $_COOKIE ) ) $_COOKIE = strip_magic_quotes( $_COOKIE );
}

Download snippet

Download Snippet: magic_quotes_inc.txt
More information: Magic Quotes on wikipedia.org

Posted by Stig Lindqvist Posted in: Snippets No Comments » June 2008