php filter extension

昨天说到php5.2.0新捆绑了filter extension,于是花时间看了看filter extension的介绍。filter可以极大的简化表单验证的code,尤其是对php新手而言,对提高程序的安全性很有帮助,远离sql注入和不充分的字符过滤。它目前有下面几个api:

filter_data -- Filters data with a specified filter
input_filters_list -- Returns a list of all supported filters
input_get_args -- Gets multiple variables from outside PHP and optionally filters them
input_get -- Gets variable from outside PHP and optionally filters it
input_has_variable -- Checks if variable of specified type exists
input_name_to_filter -- Returns the filter ID belonging to a named filter

下面拣重要的说说我的学习心得:

filter_data

filter_data的函数说明:
mixed filter_data ( mixed variable, int filter [, mixed filter_options [, string charset]] )

  • variable:待过滤的字符,如果是数组,则会被递归的执行过滤操作,这个是相当方便的设置
  • filter:过滤器的id,比如FILTER_VALIDATE_EMAIL表示过滤email,FILTER_VALIDATE_URL表示过滤url
  • filter_options:没看明白干嘛的,期待有高人指点
  • charset:字符集,暂时没用。

例子:

PHP:
  1. <?php
  2. var_dump(filter_data('bob@example.com', FILTER_VALIDATE_EMAIL));
  3. var_dump(filter_data('xxx.com', FILTER_VALIDATE_EMAIL));
  4. ?>

这个例子会获得类似的输出内容:

string(15) "bob@example.com"
NULL

其中字符串“xxx.com”因为不是邮件格式,因此被过滤为null

input_get

这个函数用来获取外部变量,如post,get之类的,说明:
mixed input_get ( int type, string variable_name [, int filter [, mixed flags [, string charset]]] )

  • type:可以是其中一种 -- INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV, INPUT_SESSION,还有一个99,目前是用来对$_REQUEST进行过滤,不知道正式版会不会有变动,暂时别用
  • variable_name:变量名
  • filter:同filter_data,缺省是FILTER_DEFAULT
  • flags:没看到实例,不敢胡乱揣测
  • charset:同filter_data

借手册上的例子说话:

PHP:
  1. <?php
  2. $search_html = input_get(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
  3. $search_url = input_get(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
  4. echo "You have searched for $search_html.\n";
  5. echo "<a href='?search=$search_url'>Search again.</a>";
  6. ?>

输出:

You have searched for Me &#38; son.<br /> <a href='?search=Me%20%26%20son'>Search again.</a>

在上面的代码中,$_GET['search']分别被两种不同过滤器过滤,产生的值也不相同,第一行的filter执行了类htmlspecialchars的操作,第二行则进行了urlencode操作

input_get_args

这个函数属于进阶的用法,如果能掌握,将大大的简化代码,使用方法类似于Pear::Validate::multiple,应该是表单提交处理的主力

php 5.1.x系列能用filter extension么

filter extension在php 5.2.0之前的版本中,在pecl.php.net就存在,可以使用pear命令行直接安装:
pear install filter

这里是手册上的内容:
http://au3.php.net/manual/en/ref.filter.php

版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明

作者: Volcano 发表于July 28, 2006 at 6:53 am

版权信息: 可以任意转载, 转载时请务必以超链接形式标明文章原始出处作者信息及此声明

Tags:

1 条评论 »

  1. mint 于 2006-11-06 @ 17:38:10 留言

    http://club.phpe.net/index.php?act=ST&f=16&t=14570&s=

RSS 为此帖反馈评论

留条评论