2009/10/14
Overcoming magic_quotes_gpc
PHP offers a feature called magic_quotes_gpc. What this does is it takes all GET, POST, and COOKIE variables and applies a partial escaping to them. Unfortunately, the escaping that it does is not good enough to pass the result directly to MySQL. Further, when you run mysql_real_escape_string on the values, it will redo the escaping that magic_quotes_gpc did as well as the escaping that magic_quotes_gpc missed. For this reason, it is preferred for magic_quotes_gpc to be off. However, some hosts still use it, as it is on by default.
When magic_quotes_gpc is on with an osCommerce 3 installation, it can cause a weird looking error when editing a product with quotes or backslashes in the name or description. Each time you edit and save, it adds backslashes before all quotes and backslashes. Thus what starts as ” becomes \” and then \\\”, \\\\\\\”, and so forth. This is covered in osCommerce bug report 1010. I verified the issue and created a patch for it:
| PHP | | copy code | | ? |
| 01 | if ( ( function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() ) |
| 02 | || ( ini_get('magic_quotes_sybase') && ( strtolower(ini_get('magic_quotes_sybase')) != "off" ) ) |
| 03 | ) |
| 04 | { |
| 05 | function osc_stripslashes_callback(&$value, $key) { |
| 06 | $value = stripslashes($value); |
| 07 | } |
| 08 | |
| 09 | array_walk_recursive($_GET, 'osc_stripslashes_callback'); |
| 10 | array_walk_recursive($_POST, 'osc_stripslashes_callback'); |
| 11 | array_walk_recursive($_COOKIE, 'osc_stripslashes_callback'); |
| 12 | } |
What this code does is it checks if get_magic_quotes_gpc is on and if it is, the code undoes it by running stripslashes on all the values in the GET, POST, and COOKIE superglobal arrays (the GPC in get_magic_quotes_gpc). The code uses array_walk_recursive so that if any of the values are arrays, those get handled as well. The osc_stripslashes_callback function is created because stripslashes does not have the correct method signature to be called from array_walk_recursive.
It’s possible that the code still does not handle magic_quotes_sybase correctly. It may be that stripslashes does not cover the sybase change. If so, then it should be relatively simple to change the code to properly cover the sybase case.