William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP: callback on request

While reading mysql-real-escape-string, I found a interesting way to process web request as following:


$_GET = array_map('trim', $_GET);
$_POST = array_map('trim', $_POST);
$_COOKIE = array_map('trim', $_COOKIE);
$_REQUEST = array_map('trim', $_REQUEST);
if(get_magic_quotes_gpc()):
    $_GET = array_map('stripslashes', $_GET);
    $_POST = array_map('stripslashes', $_POST);
    $_COOKIE = array_map('stripslashes', $_COOKIE);
    $_REQUEST = array_map('stripslashes', $_REQUEST);
endif;
$_GET = array_map('mysql_real_escape_string', $_GET);
$_POST = array_map('mysql_real_escape_string', $_POST);
$_COOKIE = array_map('mysql_real_escape_string', $_COOKIE);
$_REQUEST = array_map('mysql_real_escape_string', $_REQUEST); 

PHP’s array_map function syntax:


array array_map ( callback $callback , array $arr1 [, array $... ] )

array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map().

I think above processing is not neccessary.

  • Callback function always make performance low. Drupal use callback functions to trigger events, and it is some kind of slow.
  • Not all form’s fields need to be ‘trim’ or ‘stripslashes’ or ‘mysql_real_escape_string’. Use trigger on all $_GET, $_POST, $_REQUEST exactly not a smart way.

The following is my way:


$id = $_POST['id'];
$email=isset($_POST['$email'])?$email:'';
$comment=isset($_POST['comment'])?mysql_real_escape_string(trim($_POST['comment']);
$date=format_date($_POST['date']);
...
or:
foreach($_POST as $k=>$v) {
  if(strcmp($k,'comment')==0 && $v) {
    $associate_array[$k]=mysql_real_escape_string(trim($k);
  }
  elseif(strcmp($k,'date')==0) {
    $associate_array[$k] = format_date($v);
  }
  else {
    $associate_array[$k] = $v;
  }
}

The above process is lighter and more specific.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s