PHP现在具有新的漂亮的filter_input函数,例如,现在有一个内置的FILTER_VALIDATE_EMAIL类型可以让你找到“最终的电子邮件正则表达式”

我自己的过滤器类(使用javascript来突出显示错误的字段)可以由ajax请求或普通表单发布。(见下面的例子)

/**

*  Pork.FormValidator

*  Validates arrays or properties by setting up simple arrays.

*  Note that some of the regexes are for dutch input!

*  Example:

*

*  $validations = array('name' => 'anything','email' => 'email','alias' => 'anything','pwd'=>'anything','gsm' => 'phone','birthdate' => 'date');

*  $required = array('name', 'email', 'alias', 'pwd');

*  $sanatize = array('alias');

*

*  $validator = new FormValidator($validations, $required, $sanatize);

*

*  if($validator->validate($_POST))

*  {

*      $_POST = $validator->sanatize($_POST);

*      // now do your saving, $_POST has been sanatized.

*      die($validator->getScript()."");

*  }

*  else

*  {

*      die($validator->getScript());

*  }

*

* To validate just one element:

* $validated = new FormValidator()->validate('blah@bla.', 'email');

*

* To sanatize just one element:

* $sanatized = new FormValidator()->sanatize('blah', 'string');

*

* @package pork

* @author SchizoDuckie

* @copyright SchizoDuckie 2008

* @version 1.0

* @access public

*/

class FormValidator

{

public static $regexes = Array(

'date' => "^[0-9]{1,2}[-/][0-9]{1,2}[-/][0-9]{4}\$",

'amount' => "^[-]?[0-9]+\$",

'number' => "^[-]?[0-9,]+\$",

'alfanum' => "^[0-9a-zA-Z ,.-_\\s\?\!]+\$",

'not_empty' => "[a-z0-9A-Z]+",

'words' => "^[A-Za-z]+[A-Za-z \\s]*\$",

'phone' => "^[0-9]{10,11}\$",

'zipcode' => "^[1-9][0-9]{3}[a-zA-Z]{2}\$",

'plate' => "^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}\$",

'price' => "^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?\$",

'2digitopt' => "^\d+(\,\d{2})?\$",

'2digitforce' => "^\d+\,\d\d\$",

'anything' => "^[\d\D]{1,}\$"

);

private $validations, $sanatations, $mandatories, $errors, $corrects, $fields;

public function __construct($validations=array(), $mandatories = array(), $sanatations = array())

{

$this->validations = $validations;

$this->sanatations = $sanatations;

$this->mandatories = $mandatories;

$this->errors = array();

$this->corrects = array();

}

/**

* Validates an array of items (if needed) and returns true or false

*

*/

public function validate($items)

{

$this->fields = $items;

$havefailures = false;

foreach($items as $key=>$val)

{

if((strlen($val) == 0 || array_search($key, $this->validations) === false) && array_search($key, $this->mandatories) === false)

{

$this->corrects[] = $key;

continue;

}

$result = self::validateItem($val, $this->validations[$key]);

if($result === false) {

$havefailures = true;

$this->addError($key, $this->validations[$key]);

}

else

{

$this->corrects[] = $key;

}

}

return(!$havefailures);

}

/**

*

*  Adds unvalidated class to thos elements that are not validated. Removes them from classes that are.

*/

public function getScript() {

if(!empty($this->errors))

{

$errors = array();

foreach($this->errors as $key=>$val) { $errors[] = "'INPUT[name={$key}]'"; }

$output = '$$('.implode(',', $errors).').addClass("unvalidated");';

$output .= "new FormValidator().showMessage();";

}

if(!empty($this->corrects))

{

$corrects = array();

foreach($this->corrects as $key) { $corrects[] = "'INPUT[name={$key}]'"; }

$output .= '$$('.implode(',', $corrects).').removeClass("unvalidated");';

}

$output = "";

return($output);

}

/**

*

* Sanatizes an array of items according to the $this->sanatations

* sanatations will be standard of type string, but can also be specified.

* For ease of use, this syntax is accepted:

* $sanatations = array('fieldname', 'otherfieldname'=>'float');

*/

public function sanatize($items)

{

foreach($items as $key=>$val)

{

if(array_search($key, $this->sanatations) === false && !array_key_exists($key, $this->sanatations)) continue;

$items[$key] = self::sanatizeItem($val, $this->validations[$key]);

}

return($items);

}

/**

*

* Adds an error to the errors array.

*/

private function addError($field, $type='string')

{

$this->errors[$field] = $type;

}

/**

*

* Sanatize a single var according to $type.

* Allows for static calling to allow simple sanatization

*/

public static function sanatizeItem($var, $type)

{

$flags = NULL;

switch($type)

{

case 'url':

$filter = FILTER_SANITIZE_URL;

break;

case 'int':

$filter = FILTER_SANITIZE_NUMBER_INT;

break;

case 'float':

$filter = FILTER_SANITIZE_NUMBER_FLOAT;

$flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND;

break;

case 'email':

$var = substr($var, 0, 254);

$filter = FILTER_SANITIZE_EMAIL;

break;

case 'string':

default:

$filter = FILTER_SANITIZE_STRING;

$flags = FILTER_FLAG_NO_ENCODE_QUOTES;

break;

}

$output = filter_var($var, $filter, $flags);

return($output);

}

/**

*

* Validates a single var according to $type.

* Allows for static calling to allow simple validation.

*

*/

public static function validateItem($var, $type)

{

if(array_key_exists($type, self::$regexes))

{

$returnval =  filter_var($var, FILTER_VALIDATE_REGEXP, array("options"=> array("regexp"=>'!'.self::$regexes[$type].'!i'))) !== false;

return($returnval);

}

$filter = false;

switch($type)

{

case 'email':

$var = substr($var, 0, 254);

$filter = FILTER_VALIDATE_EMAIL;

break;

case 'int':

$filter = FILTER_VALIDATE_INT;

break;

case 'boolean':

$filter = FILTER_VALIDATE_BOOLEAN;

break;

case 'ip':

$filter = FILTER_VALIDATE_IP;

break;

case 'url':

$filter = FILTER_VALIDATE_URL;

break;

}

return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false;

}

}

当然,请记住,您需要进行sql查询转义,具体取决于您使用的数据库类型(例如,mysql_real_escape_string()对于SQL Server无用)。您可能希望在适当的应用程序层(如ORM)自动处理此问题。另外,如上所述:输出到html使用其他php专用函数,如htmlspecialchars;)

对于真正允许带有类似剥离类和/或标记的HTML输入,取决于其中一个专用的xss验证包。不要把你自己的规则写成PARSE HTML!

php 清空输入缓存,用PHP清理用户输入的最佳方法是什么?相关推荐

  1. 请编写程序,读入CSV文件中数据,循环获得用户输入,直至用户直接输入“Q”退出。根据用户输入的星座名称,输出此星座的出生日期范围及对应字符形式。如果输入的名称有误,请输出“输入星座名称有误”

    星座,开始月日,结束月日,Unicode ‌水瓶座,120,218,9810 ‌双鱼座,219,320,9811 ‌白羊座,321,419,9800 ‌金牛座,420,520,9801 ‌双子座,52 ...

  2. python 用户输入_Python中如何让用户输入内容

    在使用python的时候,有时候我们需要和用户进行交互,让用户输入一些内容,然后根据内容在做处理.下面小编就给大家介绍在Python中如何让用户输入内容. 工具/原料 Ubuntu终端 方法/步骤 1 ...

  3. python输入月份判断季节_用户输入月份,判断这个月是哪个季节。(要求使用列表)_学小易找答案...

    [单选题]图 中所示电路的戴维南等效电路,用 U . I 和 R 表达出戴维南等效电路的开路电压 U OC 和等效电阻 R O .正确的是( ). [单选题]甲百货公司是增值税一般纳税人,本年7月直接 ...

  4. 自定义日期输入控件-解决需要用户输入日期的麻烦控制

    一般情况下使用文本框的,由于但无法很好的控制用户输入的格式通常都会写一个输入格式的说明如:1999-12-12,虽然用多个组合的下拉菜单可以解决问题,但是似乎不太方便操作.后来用梅花雨的日期控件,确实 ...

  5. python等待用户输入_Python等待时间,等待用户输入

    python等待用户输入 Sometimes we want our python program to wait for a specific time before executing the n ...

  6. html读取用户输入,HTML表单处理用户输入(示例代码)

    1.HTML表单用于收集用户输入.通过 标签定义 2. 元素是最重要的文本元素. 2.1.text定义常规文本输入,password定义密码字段 User name: User password: 2 ...

  7. python字典输入学生信息_Python使用用户输入来填充字典(69)

    可使用while循环提示用户输入任意数量的信息,收集起来的信息可用于形成字典便于我们调用. python大大的图 图片发自简书App 我的图 图片发自简书App 这个程序首先定义了一个空字典(resp ...

  8. linux下的缓存机制及清理buffer/cache/swap的方法梳理

    1)缓存机制介绍 在Linux系统中,为了提高文件系统性能,内核利用一部分物理内存分配出缓冲区,用于缓存系统操作和数据文件,当内核收到读写的请求时,内核先去缓存区找是否有请求的数据,有就直接返回,如果 ...

  9. python获取用户输入中文_python中的用户输入

    一个选项(ha!)将选项的结构存储在变量中.在 例如,(在您的脑海中)将"菜单"定义为包含以下值的子集的dict:"问题"-这是显示菜单时要问的问题-" ...

最新文章

  1. 【SD】自定义销售订单审批状态
  2. HttpClient测试类请求端和服务端即可能出现乱码的解决
  3. [密码学基础][每个信息安全博士生应该知道的52件事][Bristol Cryptography][第4篇] P类复杂问题
  4. HDFS-文件读写过程
  5. php多维数组交集,求数组差/交集函数-php数组函数(二)
  6. 如何通过虚拟私有云保障服务安全【华为云分享】
  7. redis 参数配置总结
  8. eclipse中导入maven项目时pom文件报错
  9. CUDA编译器nvcc的用法用例与问题简答
  10. 安装redis 5.0.5版本 真香警告
  11. “C语言之父”40年前搞的操作系统复活,Linux、Windows都借鉴过它
  12. 【DZS-12CE/S DC220V型直流回路监视继电器】
  13. 对堆区、栈区、全局静态区的理解
  14. 2022年电工(技师)考试题及电工(技师)模拟试题
  15. Linux Socket详解 大全 基础知识
  16. 使用python的zipfile模块巧解word批量生成问题
  17. C# SharpZipLib 压缩中文文件名乱码的解决办法(必看 实测有用)
  18. Redis几种集群模式
  19. 如何实现ADSL宽带用户开机自动拨号与定时拨号
  20. 群晖Docker 容器时间 时区不对解决方法

热门文章

  1. 消息队列系列(三):.Rabbitmq Trace的使用
  2. SqlServer判断表是否存在
  3. cocos2d-x自制工具03:AnimatePacker for Mac/Win32 v1.1 Build1发布!
  4. Control usage: (1) Windows Phone 7: Popup control
  5. Oracle宣布终止所有Intel Itanium平台上的软件开发
  6. Loadrunner常见的乱码问题
  7. Opera 60 正式发布,代号 Reborn 3
  8. Spring 是如何解决并发访问的线程安全性问题的
  9. MySQL:Database connections will be migrated官方说明
  10. Veeam Backup Replication v7 安装配置手册