Coping with Magic Quotes


Coping with "Magic Quotes"

 if (get_magic_quotes_gpc()) {   $_GET  = stripFormSlashes($_GET);   $_POST = stripFormSlashes($_POST); } 


If the configuration setting magic_quotes is set to "On", all data coming in from external sources, including form data and cookies, gets special treatment. All quote characters, " and ', are escaped using the backslash character (\). Therefore, if the user enters It's my life into a text field, the value found in $_GET or $_POST is It\'s my life. This was originally implemented to avoid Structured Query Language (SQL) injection (see Chapter 8, "Using XML," for more details on that), but isespecially for experienced programmersvery annoying. The only thing that is even more annoying is to remove these quotes manually for every form field.

Stripping Slashes, If They Were Added by "Magic Quotes" (stripFormSlashes.inc.php)
 <?php   function stripFormSlashes($arr) {     if (!is_array($arr)) {       return stripslashes($arr);     } else {       return array_map('stripFormSlashes', $arr);     }   }   if (get_magic_quotes_gpc()) {     $_GET  = stripFormSlashes($_GET);     $_POST = stripFormSlashes($_POST);   } ?> 

The PHP function stripslashes() removes escape backslashes from strings. However, this function can only be called if "magic quotes" have been applied; otherwise, it destroys backslashes that were added on purpose. You can determine whether "magic quotes" are active by calling the Boolean function get_magic_quotes_gpc(). If this returns TRue, all slashes can be removed. To make this as convenient as possible, you can put this in a universal function called stripFormSlashes(). Using array_map(), all elements of an array are unslashed.

This file can then be included into all files that are processing form data and takes care of all "magic quotes" automatically.




PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net