Pages

Sunday, February 27, 2011

Magic Quotes in PHP

What is Magic Quotes?: 
When turned on, Magic Quotes automatically performs an addslashes () on all form data submitted. This means that a [\] is placed before every ['], ["], [\], or nul in the data, so That's Great would be converted to That\'s Great automatically. This all happens before your coding even sees that data, so if you're just passing a string to the next page (and not to a database) it will print out with slashes even though you may not want them.

Why is it Good?: 
If Magic Quotes is running, you can be sure that you won't get any SQL errors due to illegal characters slipping by without a backslash. It saves having to run addslashes () on all the form data that's going to your database.

Why is it Bad?: 
You shouldn't learn to rely on Magic Quotes, or you won't learn to program without it. Also, when you let something automated run, your handing over control. It may seem easy now, but in the long run you may regret it. Plus, you may not always want slashes added, because not all forms go to MySQL, some just pass data to email or echo it on another page.

What about stripslashes (): 
Perhaps your asking, if Magic Quotes is running, why don't I just run stripslashes () on the data I don't want it on? You're right, this does work... BUT do you really want to make sure your running this on every script you ever run, and redo everything you already have running?

How do I know if it's on?: 
If when you run addslashes () you're getting three backslashes instead of one, it's probably running. You can check for sure in your phpinfo () or by running get_magic_quotes_gpc().

How do I turn it off?: 
If you have access to your php.ini file you can edit it to set magic_quotes_gpc = Off. You could also try doing it from your .htaccess by adding the line php_flag magic_quotes_gpc Off. Or when in doubt, contact your hosting provider.

No comments:

Post a Comment