Magic quotes in PHP

2019-01-04 01:09发布

According to the PHP manual, in order to make code more portable, they recommend using something like the following for escaping data:

if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}

I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string().

12条回答
2楼-- · 2019-01-04 01:14

Just found this over on the PHP manual pages, looks like a pretty clever way to strip em (deals with keys and values...):

if (get_magic_quotes_gpc())
{
    $_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);
    ini_set('magic_quotes_gpc', 0);
}
查看更多
够拽才男人
3楼-- · 2019-01-04 01:15

"I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string()"

Also addslashes can be tricked as well check out this post:

http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string

查看更多
叛逆
4楼-- · 2019-01-04 01:17

Right, it's not the best way to do it and not the most secure. Escaping is best done in relation to what you are escaping for. If it is to store in a mysql database, use mysql_real_escape_string which takes into account other locales, character sets. For HTML, htmlentities. For use in code, escapeshellcmd, escapeshellarg. Yes, you probably need to stirpslashes first if magic quotes is on. But best not to count on it or use it.

查看更多
爷的心禁止访问
5楼-- · 2019-01-04 01:18

Prepared statements of PDO and Mysqli are the better way to prevent SQL injection.

But if you are migrating a legacy code which is base on Magic Quotes for every SQL queries, you can refer yidas/php-magic-quotes for implementing Magic Quotes on the environment with PHP 5.4 above version.

https://github.com/yidas/php-magic-quotes

查看更多
我只想做你的唯一
6楼-- · 2019-01-04 01:22

Regarding using a database specific escaping function, you pretty much need to. I have found just using addslashes() to fail in rare cases with MySQL. You can write a function to escape which determines which DB you are using and then use the approriate escape function.

查看更多
SAY GOODBYE
7楼-- · 2019-01-04 01:23

You may try this:

if (get_magic_quotes_gpc()) { 
          $_REQUEST = array_map('stripslashes', $_REQUEST); 
          $_GET = array_map('stripslashes', $_GET);
          $_POST = array_map('stripslashes', $_POST);
          $_GET = array_map('stripslashes', $_COOKIES);

    }
查看更多
登录 后发表回答