Magic quotes in old and new versions of PHP

this code should ensure that clean code gets into the database

it should 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 into the database without problems, but I get an error in the browser

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

is how i call 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;

}
+3
source share
2 answers

For starters, this function can be reduced to about 5 lines (it would be easier to read).

-, MySQL ? PHP, , / . 100% mysql_real_escape_string, :

, , mysql_connect(). , , mysql_connect() .

, , .

+2

, PHP 5.3+, :

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);
}

, .

0
source

Source: https://habr.com/ru/post/1723755/


All Articles