PHP: callback on request
Blogs20112011-03-17
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.
