PHP 函数 array_map() 和 call_user_func_array() 的妙用

来源:互联网 发布:java url上传文件格式 编辑:程序博客网 时间:2024/05/20 20:03

PHP 我用得比较少,今天无意在查资料时,发现一段代码,里面使用 array_map() 和 call_user_func_array(),巧妙得实现了一段简洁的回调函数使用实例。看到这段代码,让我的感觉是非常舒服,像是得到了一份无比美味又赏心悦目的美食。

PHP的官方帮助文档,可以由用户添加笔记,里面经常会有很经典的代码,这种方式确实不错。


下段代码的地址:http://cn2.php.net/manual/en/function.sprintf.php#93156


I created this function a while back to save on having to combine mysql_real_escape_string onto all the params passed into a sprintf. it works literally the same as the sprintf other than that it doesn't require you to escape your inputs. Hope its of some use to people


<?php
function mressf()
{
    
$args func_get_args();
    if (
count($args) < 2)
        return 
false;
    
$query array_shift($args);
    
$args array_map('mysql_real_escape_string'$args);
    
array_unshift($args$query);
    
$query call_user_func_array('sprintf'$args);
    return 
$query;
}
?>

Regards
Jay

Jaygilford.com


说明:

这段代码的用意是对 mysql 的查询语句中所出现的参数进行转义操作,以避免数据库注入攻击。

这段函数,对参数数目的要求是必须大于2个,第一个是 含 sprintf 格式化语法的字符串,后面则跟需格式化的参数值。

$query array_shift($args);  // 取出传入的第一个参数(SQL语句),$args 只留下其它SQL语句对应的参数

$args array_map('mysql_real_escape_string'$args); // 对数组中的所有值,调用 mysql_real_escape_string 分别进行转义处理,再返回对应的数组

array_unshift($args$query);  // 将 SQL 语句放回到 $args 数组中,成为数组的第一项。

$query call_user_func_array('sprintf'$args); // 再调用函数 sprintf ,并将数组作为传入参数。


使用例:

printf(mressf("select * from users where username='%s' and password='%s'", 'username', "password' OR '1'='1"));

输出应该是:(注:未验证)

select * from users where username='username' and password='password\' OR \'1\'=\'1'

0 0
原创粉丝点击