Magic quotes on older and new versions of PHP

461 views Asked by At

this code is supposed to ensure that clean code gets to the database

it is supposed to work in earlier versions of PHP (earlier than 4.3.0) and later versions of php (older than 4.3.0)

it works well because the data gets to the database without a problem but i get an error on the browser

$menu_name = mysql_prep($_POST['menu_name']);

is how i call the mysql_prep function

function mysql_prep($value)
{

    $get_magic_quotes = get_magic_quotes_gpc();

    $new_enough_php = function_exists ("mysql_real_escape_string");  //check if php version is greater than 4.3.0

    if($new_enough_php) // if php is of a newer version 
    {
        //undo magic quotes effect so that mysql_real_escape_string can work well
        if ($get_magic_quotes)
        {
            $value = stripslashes ($value);
        }

        $value = mysql_real_escape_string($value);

    }
    else //mysql is older than 4.3.0    
    {
        //add slashes manually if magic quotes are off
        if(!$get_magic_quotes)
        {
            $value = addslashes ($value);
        }
        //if magic quotes already exist, slashes already exists
    }

    return $value;

    //$value = mysql_real_escape_string($value);

    //$value_without_slashes = stripslashes ($value);

    //return $value_without_slashes;

}
2

There are 2 answers

0
DisgruntledGoat On BEST ANSWER

For starters, that function could be shortened to about 5 lines (it would be easier to read, too).

Secondly, are you connected to MySQL when you call that function? You must be connected for PHP to know how/what to escape. It's not 100% clear from the manual for mysql_real_escape_string, but it is implied:

If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments.

If that still doesn't solve it, I suggest printing the query prior to executing it and checking everything is in order.

0
Alix Axel On

You shouldn't do that inside a DB method, if you're running PHP 5.3+ you can place this code on the topmost of your page:

if (get_magic_quotes_gpc() === 1)
{
    $_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
    $_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);
    $_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);
    $_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);
}

It handles magic quotes in keys, values and multi-dimensional arrays.