PHP Magic Quotes theory and the operation
One of the known PHP developer’s problems are the quotes and double quotes. It was a sunshine day when we started developing our Twitter related application allowed to users tweet from code tweets that are more than 140 characters.
Everything worked smooth until somewone typed something like this : Check out my new track “VNV Nation- Electronaut
Yes, he forgot to close double quotes. Thanks to MySQL error functions, insertion wasn’t done to mysql and it had shown an error.
Magic quotes comes to solve this problem, there are other better methods probably, but it is quiet good for simple applications without complicating string editing functions.
So how to deal with Magic Quotes ?
First we should check if magic quotes are enabled. There are two methods to do that. You can check from code typing
<?php if(get_magic_quotes_gpc()) echo "Enabled"; else echo "Disabled"; ?>
The second method also could be done from code :
<?php
echo phpinfo();
?>
The second method will execute and print basic server PHP configuration information, browse through file and find magic_quotes it should be on or off.
Most of the hosting companies enable magic_quotes function in server php.ini by default.
Lets create simple example on how magic_quotes work.
<?php echo $_POST['string']; ?> <form action='' method='post'> Type something: <input type='text' name='string'/> <input type='submit'> </form>
The output will be something like that : Check out my new track \”VNV Nation- Electronaut
We will probably want to remove ugly backslashes from string in output ( if you work with mysql database , remove slashes when you make a query call )
Code without slashes :
<?php echo stripslashes($_POST['string']); ?> <form action='' method='post'> Type something: <input type='text' name='string'/> <input type='submit'> </form>
And a little bit smarter code :
<?php
if(get_magic_quotes_gpc())
echo stripslashes($_POST['string']);
else
echo $_POST['string'];
?>
<form action='' method='post'>
Type something: <input type='text' name='string'/>
<input type='submit'>
</form>
You will probably want to create your own magic quotes function :
<?php
function magic_string($string)
{
if(get_magic_quotes_gpc()) return stripslashes($string); else return $string;}
?>
We have shown the basic operations of magic quotes usage, please post your examples in comments.
Good luck coding.
