Delete backslashs : death to magic_quotes_gpc
Le octobre 30th, 2008Even in PHP 5, this old security params is activated by default, and I hate it. It’s Magic Quote.
When this flag is On, then vars in cookies, from a form or a url, are automatically « escaped ».
It means that backslashes are added before some special characters. Primary: the simple quote.
Example : my script toto.php contains this code : Bonjour <?= $_GET[‘nom’] ?> !.
Calling : toto.php?nom=Bob ; outputs Bonjour Bob !
Calling : toto.php?nom=Muad’ib ; outputs Bonjour Muad\’ib !
Why ? Because leaving ‘ unescaped can lead to SQL injection if the coder didn’t code well.
But I code well, and I add myself, and only when necessary the backslashes. Problem : with this flag, slashes are added two times, and it gives this : Muad\\\’ib
In order to get ride of the slashes, I use often this code :
if (get_magic_quotes_gpc()) $_POST = array_map('kill_magic_quotes', $_POST); function kill_magic_quotes($v) { return is_array($v) ? array_map('kill_magic_quotes', $v) : stripslashes($v); } |
But now on my owns servers, I simply turn the flag Off.
Except ! Sometime with a new machine, I forget this, and some data in database is now full of ‘ ….
So I wrote a script for command-line. Its parameters are a table name, and a field name.
It checks for errors, it’s cool and well done. Voilà.
You can download the code here :
The script in command line is launched like this :
php del_slashs.php tablename fieldname |
Put sqlQueries.php file in the same folder, and edit del_slash.php to put your database connection information.
Leave a Reply