Zend_Filter_Input
为输入数据过滤提供了便捷的结构化方法。其目的是多方面的,主要是为了满足三类不同人群的需求:
开发者
虽然,过滤输入数据不像什么都不做那样简单,但是开发人员必须确保数据的完整性,同时又不添加复杂的代码。
管理者
那些需要维持对一个庞大的开发小组的控制的管理者,能够通过限制或者禁止直接访问原始数据,来强制执行一种结构化的方法,对输入数据进行过滤。
审核员
审核员,需要快速且正确地确定开发者何时何地使用了原始数据。 Zend_Filter_Input使代码变得更加的清晰的同时,帮助了审核员明确区分了不同的输入数据过滤方法。
有多种方法来过滤输入数据,同样PHP开发者也可使用多种方法。白名单过滤,黑名单过滤,正则表达式,条件语句,PHP函数,这些只仅仅是输入数据过滤的一部分例子。
为了为输入数据的过滤提供一个结构化的方法,Zend_Filter_Input
默认地设置源数据数组为null
,试图对输入数据的访问加强控制。
在默认的(严格的)方法中,只有一个参数-需要过滤的数据的数组,被传递给构造器。未过滤的数据只能通过getRaw()
方法来访问。
<?php // $_POST['email'] === 'webmaster@example.com' // Filter the $_POST data array require_once 'Zend/Filter/Input.php'; $filterPost = new Zend_Filter_Input($_POST); // $_POST is now null echo null === $_POST ? 'yes' : 'no'; // prints 'yes' // Get the raw e-mail value echo $filterPost->getRaw('email'); // prints 'webmaster@example.com'
Zend_Filter_Input
设置被传递的$_POST
数组为null
,也就不可能再直接访问它了。(原始的数据只能通过getRaw()
方法访问)
在可选的方法(不严格的)中,false
被当作第二个参数传递给构造器:
<?php // $_POST['email'] === 'webmaster@example.com' // Filter the $_POST data array require_once 'Zend/Filter/Input.php'; $filterPost = new Zend_Filter_Input($_POST, false); // $_POST remains not null echo null === $_POST ? 'yes' : 'no'; // prints 'no' // Get the raw e-mail value echo $filterPost->getRaw('email'); // prints 'webmaster@example.com'
过滤器的使用还是相同的,但Zend_Filter_Input
不设置原始数组$_POST的值为 null
,所以开发人员还可以直接访问$_POST
。这个方法是不赞成的,我们应该使用默认的(严格的)方法。
Zend_Filter_Input
被设计成主要用来过滤数组的。许多源数据也都是藏在PHP超级数组下的($_GET
,
$_POST
, $_COOKIE
等等),同时数组也通常被用来储存来自其他源的输入数据。如果你要过滤一个标量,参见第 11 章 Zend_Filter。