PHP Security: Remove Default Escaping In PHP

Reading this first may be helpful!
Remove default PHP escaping and apply your own at runtime. This way you are safe at client's setting of magic quote in their php.ini.
PHP has default escaping functionality. It escapes all incoming data.

It is preferred not to use default magic quote 'On' in PHP. In PHP 6.0.0 it will not be available. Escape your data on runtime according to your need.

Remove the PHP's default magic quotes:


<?php
function remove_magic_quotes($arr) {
 foreach ($arr as $k=>$v) {
  if (is_array($v))
   $arr[$k] = remove_magic_quotes($v);
  else
   $arr[$k] = stripslashes($v);
 }
 return $arr;
}
if (get_magic_quotes_gpc()) {
 // Remove PHP default escaping
 $_REQUEST = remove_magic_quotes($_REQUEST) ;
 $_GET     = remove_magic_quotes($_GET);
 $_POST    = remove_magic_quotes($_POST);
 set_magic_quotes_runtime(0);
}
?>
If you use this code at the top of the php page then default magic quote is treated as off. You can also set php_magic_quotes off in php.ini file.

Now, use data escaping according to your need:


<?php
// Now code for output to database
function quoteIt ($val) {
 if (! is_numeric($val)) {
  // Prepends backslashes to the following characters: x00, n, r, , ', " and x1a.
  $val = "'" . mysql_real_escape_string ($val) . "'";
 }
 return $val;
}
// For code html output, use this:
function htmlEscape ($val) {
 return htmlspecialchars($val, ENT_QUOTES, 'ISO-8859-1');
 //  ISO-8859-1 will be your Content-Type value used in response.
 // htmlspecialchars translates ", ', <, > and &.
}
?>
quoteIt() function can be used in mysql queries directly like this:
$query = "select * from table where name =" . quoteIt($_POST['name']) . " and age=30";

Related:
PHP Security: Cross-Site scripting

Comments are open for an year period. Please, write here on Facebook page.