PHP

The Magic Quotes

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

Magic Quotes automatically escapes incoming data (GET, POST, COOKIE or external source, including databases and text files) to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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 tutorial 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"

<?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.