alixaxel / phunction

Small and carefully designed PHP 5.2+ HMVC framework.
//github.com/alixaxel/phunction/
MIT License
105 stars 10 forks source link

magic_quotes_gpc and JSON #1

Closed alixaxel closed 13 years ago

alixaxel commented 13 years ago

In PHP 5.3+ and when magic_quotes_gpc is "On" control characters also get their slashes removed.

This issue might be solved by either double escaping control characters prior to calling json_decode(), or, by dropping the current JSON magic quotes removal strategy altogether.

alixaxel commented 13 years ago

Double escaping can be done with the following str_replace():

$_GET = json_decode(stripslashes(str_replace(array('\\0', '\\a', '\\b', '\\f', '\\n', '\\r', '\\t', '\\v'), array('\\\0', '\\\a', '\\\b', '\\\f', '\\\n', '\\\r', '\\\t', '\\\v'), json_encode($_GET, JSON_HEX_APOS | JSON_HEX_QUOT))), true);
$_POST = json_decode(stripslashes(str_replace(array('\\0', '\\a', '\\b', '\\f', '\\n', '\\r', '\\t', '\\v'), array('\\\0', '\\\a', '\\\b', '\\\f', '\\\n', '\\\r', '\\\t', '\\\v'), json_encode($_POST, JSON_HEX_APOS | JSON_HEX_QUOT))), true);
$_COOKIE = json_decode(stripslashes(str_replace(array('\\0', '\\a', '\\b', '\\f', '\\n', '\\r', '\\t', '\\v'), array('\\\0', '\\\a', '\\\b', '\\\f', '\\\n', '\\\r', '\\\t', '\\\v'), json_encode($_COOKIE, JSON_HEX_APOS | JSON_HEX_QUOT))), true);
$_REQUEST = json_decode(stripslashes(str_replace(array('\\0', '\\a', '\\b', '\\f', '\\n', '\\r', '\\t', '\\v'), array('\\\0', '\\\a', '\\\b', '\\\f', '\\\n', '\\\r', '\\\t', '\\\v'), json_encode($_REQUEST, JSON_HEX_APOS | JSON_HEX_QUOT))), true);

Alternatively, the following preg_replace() could be used:

$_GET = json_decode(stripslashes(preg_replace('~\\\(?:0|a|b|f|n|r|t|v)~', '\\\$0', json_encode($_GET, JSON_HEX_APOS | JSON_HEX_QUOT))), true);
$_POST = json_decode(stripslashes(preg_replace('~\\\(?:0|a|b|f|n|r|t|v)~', '\\\$0', json_encode($_POST, JSON_HEX_APOS | JSON_HEX_QUOT))), true);
$_COOKIE = json_decode(stripslashes(preg_replace('~\\\(?:0|a|b|f|n|r|t|v)~', '\\\$0', json_encode($_COOKIE, JSON_HEX_APOS | JSON_HEX_QUOT))), true);
$_REQUEST = json_decode(stripslashes(preg_replace('~\\\(?:0|a|b|f|n|r|t|v)~', '\\\$0', json_encode($_REQUEST, JSON_HEX_APOS | JSON_HEX_QUOT))), true);
alixaxel commented 13 years ago

Fixed in version 1.4.21.

alixaxel commented 13 years ago

Since the magic_quotes_gpc also affects some built-in functions (namely parse_str(), addslashes() and stripslashes()) this logic has been replaced by the recursive phunction::Voodoo() method, which is also called in the phunction::__construct() for the $_GET, $GLOBALS['_PUT'], $_POST, $_COOKIE and $_REQUEST superglobals.

phunction::Voodoo() should also be called once on the return value of any other affected function - specially parse_str().