Tuesday, January 26, 2010

11:42 PM
Magic quotes would automatically escape risky form data that might be used for SQL Injection with a backslash \. The characters escaped by PHP include: quote ', double quote ", backslash \ and NULL characters.
you need to check to see if you have magic quotes enabled on you server. The get_magic_quotes_gpc function will return a 0 (off) or a 1 (on). These boolean values will fit nicely into an if statement where 1 is true and 0 is false.

Example:

if(get_magic_quotes_gpc())
echo "Magic quotes are enabled";
else
echo "Magic quotes are disabled";


If you received the message "Magic quotes are enabled" then you should definitely continue reading this lesson, if not feel free to learn about it in case you are developing for servers that might have quotes on or off.


Magic quotes in action :

Now lets make a simple form processor to show how machines with magic quotes enabled will escape those potentially risky characters. This form submits to itself, so you only need to make one file, "magic-quotes.php" to test it out.

magic-quotes.php Code:

<?php
echo "Altered Text: ".$_POST['question'];
?>

<form method='post'>
Question: <input type='text' name='question'/><br />
<input type='submit'>

</form>

This simple form will display to you what magic quotes is doing. If you were to enter and submit the string: Sandy said, "It's a beautiful day outside and I like to use \'s." You would receive the following output.


Removing backslashes - stripslashes()

Before you use PHP's backslash removal function stripslashes it's smart to add some magic quote checking like our "Are They Enabled?" section above. This way you won't accidentally be removing slashes that are legitimate in the future if your PHP's magic quotes setting changes in the future.

Magic-quotes.php Code:

<?php
echo "Removed Slashes: ";
// Remove those slashes
if(get_magic_quotes_gpc())
echo stripslashes($_POST['question']);
else
echo $_POST['question'];
?>

<form method='post'>
Question: <input type='text' name='question'/><br />
<input type='submit'>

</form>

0 comments: