在java中实现过滤器,很简单,只需要在web.xml中配置如:
<filter> <filter-name>iSpaceAuth</filter-name> <filter-class> com.skylark.console.servlet.ISpaceLoginFilter </filter-class> </filter> <filter-mapping> <filter-name>iSpaceAuth</filter-name> <url-pattern>/console/*</url-pattern> </filter-mapping>
要想在PHP中实现一个类似的功能,因为我的需求是这样的,有个开发好了的OA系统,要集成到我们的应用中,OA要对外来的数据进行过滤,在给自己处理。这样就等于我必须写一个Php文件进行过滤,然后OA系统的文件都必须include该文件。这多恐怖,要重复的改好多代码,而且,代码的耦合度相当的高。
查找PHP手册发现了有一些过滤的东西,
一、过滤函数
filter_has_var — Checks if variable of specified type exists 检查变量是否是指定的类型
filter_id — Returns the filter ID belonging to a named filter 通过过滤器名得到过滤器的ID
filter_input_array — Gets external variables and optionally filters them
filter_input — Gets a specific external variable by name and optionally filters it
filter_list — Returns a list of all supported filters 返回支持的过滤器列表
filter_var_array — Gets multiple variables and optionally filters them 得到多个变量的值,每个变量选择一个过滤器
filter_var — Filters a variable with a specified filter 用指定的过滤器过滤变量
以前没使用过这个东东,今天试用下。
<?php function convertSpace($string){ return str_replace("_", " ", $string); } $string = "Peter_is_a_great_guy!"; echo filter_var($string, FILTER_CALLBACK,array("options"=>"convertSpace")); ?>
会输出 Peter is a great guy!
发现PHP提供的过滤器只是对输入数据的过滤。不能像java一样,对整个项目访问进行过滤。java的过
滤器还能指定过滤规则。看到这个规则让我想起了apache有个rewrite_rules的模块。让所有的访问都
重定向到一个文件,那个文件就相当于一个过滤器了。我个那个文件取名filter
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)host [NC]
RewriteRule ^(.*) filter.php
虽然这样是可以实现。但是文件的组织方式必须是有规则的,就像单入口访问一样的。通过在filter.php通过new一个访问对象,
调用一个方法来访问页面。
单入口的代码
<?php require_once './config.php'; $act = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'index'; $ctl = isset($_REQUEST['ctl']) ? trim($_REQUEST['ctl']) : 'default'; $ctl = strtolower($ctl); $act = strtolower($act); require_once ROOTPATH.'/'.'lib'.'/controller/'.$ctl.'.php'; $ctl = ucfirst($ctl).'Controller'; $act = $act.'Action'; $app = new $ctl($act);
但是该OA实现的不是单入口访问。这样的话访问的页面就一直是filter.php跳转之后又跳回来了。
最后在发现在PHP的配置文件php.ini中可以配置 auto_prepend_file,该值的作用是在每个文件访问
之前include该文件。这样include的文件就相当一个过滤器了。哈哈!该配置文件要重启服务啊,有点
郁闷,那有没有改了之后不用重启服务的方法呢?当然有了,那就是采用.htaccess文件了。配置如
下。
RewriteEngine on php_value auto_prepend_file "D:/web/htdocs/demo1/filter.php"
下面我们来测试下。我建个项目叫demo该项目下的文件有
index.php
<?php echo "index.php \n";
filter.php 代码
<?php echo 'filter'."\n"; $fileName = pathinfo($_SERVER['SCRIPT_FILENAME']); if($fileName['filename'] == 'index') { header("location:".'./test.php'); }
test.php
<?php echo 'test';
我们在url 中输入 http://localhost/demo/index.php
结果是:filter test
虽然实现了但是还是java的相差太多了.java的过滤器可以实现多个,这个就不行了。还可以指定哪些访
问要过滤,这个就不行了。
附:
1、apache rewrite模块的启用方法。
在http.conf文件中找到LoadModule rewrite_module modules/mod_rewrite.so把前面的# 删除。
本文探讨了在PHP中实现类似Java的过滤器功能的方法,通过利用PHP内置的filter函数和Apache的rewrite模块,以及使用auto_prepend_file配置实现全局过滤。

503

被折叠的 条评论
为什么被折叠?



