The goal is to leave the input untouched in PHP 5.2.8. Let's have this sample text given in $_POST['example']:
a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
Let's have two simple scripts:
Script A:
<?php echo $_POST['example']; ?>
Script B:
<?php echo stripslashes($_POST['example']); ?>
Let's have four different configurations and corresponding output:
Case #1:
* magic_quotes_gpc = Off
* magic_quotes_sybase = Off
A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )
Case #2
* magic_quotes_gpc = On
* magic_quotes_sybase = Off
A: a backslash ( \\ ), a single-quote ( \' ), a double-quote ( \" ) and a null character ( \\0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
Case #3
* magic_quotes_gpc = On
* magic_quotes_sybase = On
A: a backslash ( \ ), a single-quote ( '' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )
Case #4
* magic_quotes_gpc = Off
* magic_quotes_sybase = On
A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )
Conclusions:
1) we do not need to do anything, if the magic_quotes_gpc is disabled (cases 1 and 4);
2) stripslashes($_POST['example']) only works, if the magic_quotes_gpc is enabled, but the magic_quotes_sybase is disabled (case 2);
3) str_replace("''", "'", $_POST['example']) will do the trick if both the magic_quotes_gpc and the magic_quotes_sybase are enabled (case 3);
<?php
function disable_magic_quotes_gpc()
{
if (TRUE == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc())
{
$mqs = strtolower(ini_get('magic_quotes_sybase'));
if (TRUE == empty($mqs) || 'off' == $mqs)
{
}
else
{
}
}
}
?>
Important notes:
1) arrays need to be processed recursively;
2) both stripslashes and str_replace functions always return strings, so:
* TRUE will become a string "1",
* FALSE will become an empty string,
* integers and floats will become strings,
* NULL will become an empty string.
On the other hand you only need to process strings, so use the is_string function to check;
3) when dealing with other (than GPC) data sources, such as databases or text files, remember to play with the magic_quotes_runtime setting as well, see, what happens and write a corresponding function, i.e. disable_magic_quotes_runtime() or something.
4) VERY IMPORTANT: when testing, remember the null character. Otherwise your tests will be inconclusive and you may end up with... well, serious bugs :)