PHP 函数 array_map() 和 call_user_func_array() 的妙用
来源:互联网 发布:redis java开发 编辑:程序博客网 时间:2024/06/05 07:25
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'
- PHP 函数 array_map() 和 call_user_func_array() 的妙用
- PHP 函数 array_map() 和 call_user_func_array() 的妙用
- PHP中array_map的妙用
- 【php】php中call_user_func_array和call_user_func函数的用法
- call_user_func函数和call_user_func_array函数(PHP)
- PHP之call_user_func函数和call_user_func_array函数
- php函数call_user_func和call_user_func_array详解
- php函数call_user_func和call_user_func_array详解
- php函数call_user_func和call_user_func_array详解
- php函数call_user_func和call_user_func_array详解
- php函数call_user_func和call_user_func_array详解
- php函数call_user_func和call_user_func_array详解
- php函数call_user_func和call_user_func_array详解
- php函数call_user_func和call_user_func_array详解
- php自定义函数call_user_func和call_user_func_array详解
- php函数call_user_func和call_user_func_array详解
- php自定义函数call_user_func和call_user_func_array详解
- php函数call_user_func和call_user_func_array详解
- Android开发中各种问题集锦
- java创建各种数组jvm默认初始值列表
- 抽象工厂(Abstract Factory Pattern)
- HDU--1443 Joseph
- 0713
- PHP 函数 array_map() 和 call_user_func_array() 的妙用
- Android中截取当前屏幕图片
- 通信规程与通信协议
- 黑马程序员—.NET基础—06
- Android Ap 开发 设计模式
- 看到的几个题目
- 网关和路由器功能的有哪些不同
- 零基础学习SVN之(一):SCM与SVN的使用(基础篇)
- 动态代理