一个快速、可扩展且独立的PHP输入验证类,允许您验证任何数据

1.3 2015-08-06 07:06 UTC

This package is auto-updated.

Last update: 2024-09-17 21:31:45 UTC


README

GUMP是一个独立的PHP数据验证和过滤类,使得在没有框架依赖的情况下验证任何数据变得简单且不痛苦。

关注项目板: http://d.monsterboards.co/project/LSCPVmHUxQ-gump

安装GUMP有两种方式

手动安装
  1. 下载GUMP
  2. 解压并将目录复制到您的PHP项目目录中。

将GUMP包含到您的项目中

require "gump.class.php";

$is_valid = GUMP::is_valid($_POST, array(
	'username' => 'required|alpha_numeric',
	'password' => 'required|max_len,100|min_len,6'
));

if($is_valid === true) {
	// continue
} else {
	print_r($is_valid);
}
使用composer安装

将以下内容添加到您的composer.json文件中

{
    "require": {
        "wixel/gump": "dev-master"
    }
}

然后打开您的项目目录中的终端并运行

composer install

可用方法

// Shorthand validation
is_valid(array $data, array $rules) 

// Get or set the validation rules
validation_rules(array $rules); 

// Get or set the filtering rules
filter_rules(array $rules); 

// Runs the filter and validation routines
run(array $data); 

// Strips and encodes unwanted characters
xss_clean(array $data); 

// Sanitizes data and converts strings to UTF-8 (if available), 
// optionally according to the provided field whitelist
sanitize(array $input, $whitelist = NULL); 

// Validates input data according to the provided ruleset (see example)
validate(array $input, array $ruleset); 

// Filters input data according to the provided filterset (see example)
filter(array $input, array $filterset); 

// Returns human readable error text in an array or string
get_readable_errors($convert_to_string = false); 

// Fetch an array of validation errors indexed by the field names
get_errors_array();

// Override field names with readable ones for errors
set_field_name($field, $readable_name);

示例(长格式)

以下示例是注册表单的一部分,流程应该是相当标准的

# Note that filters and validators are separate rule sets and method calls. There is a good reason for this.

require "gump.class.php";

$gump = new GUMP();

$_POST = $gump->sanitize($_POST); // You don't have to sanitize, but it's safest to do so.

$gump->validation_rules(array(
	'username'    => 'required|alpha_numeric|max_len,100|min_len,6',
	'password'    => 'required|max_len,100|min_len,6',
	'email'       => 'required|valid_email',
	'gender'      => 'required|exact_len,1|contains,m f',
	'credit_card' => 'required|valid_cc'
));

$gump->filter_rules(array(
	'username' => 'trim|sanitize_string',
	'password' => 'trim',
	'email'    => 'trim|sanitize_email',
	'gender'   => 'trim',
	'bio'	   => 'noise_words'
));

$validated_data = $gump->run($_POST);

if($validated_data === false) {
	echo $gump->get_readable_errors(true);
} else {
	print_r($validated_data); // validation successful
}

示例(短格式)

短格式是运行验证的另一种方式。

$data = array(
	'street' => '6 Avondans Road'
);

$validated = GUMP::is_valid($data, array(
	'street' => 'required|street_address'
));

if($validated === true) {
	echo "Valid Street Address!";
} else {
	print_r($validated);
}

匹配数据键与规则键

通过向run方法添加一个额外参数,我们可以检查是否为每个数据键指定了规则。

$gump->run($_POST, true);

如果不匹配,输出将为

There is no validation rule for <span class=\"$field_class\">$field</span>

返回值

run()返回以下两种类型之一

数组 包含成功验证和过滤的数据,当验证成功时

布尔值 当验证失败时返回False

validate()返回以下两种类型之一

数组 包含未通过验证的数据的键名和验证器名。

您可以使用此数组以及您的语言辅助程序来确定要显示的错误消息。

布尔值 当验证成功时返回TRUE。

filter()返回与作为参数解析的$input参数相同的精确数组结构,唯一的区别是过滤后的数据。

可用验证器

  • required 确保指定的键值存在且不为空
  • valid_email 检查是否为有效的电子邮件地址
  • max_len,n 检查键值长度,确保它不大于指定的长度。n = 长度参数。
  • min_len,n 检查键值长度,确保它不短于指定的长度。n = 长度参数。
  • exact_len,n 确保键值长度精确匹配指定的长度。n = 长度参数。
  • alpha 确保键值中只包含字母字符(a-z,A-Z)
  • alpha_numeric 确保键值中只包含字母数字字符(a-z,A-Z,0-9)
  • alpha_dash 确保键值中只包含字母数字字符、破折号和下划线(a-z,A-Z,0-9,_-)
  • alpha_space 确保键值中只包含字母数字字符和空格(a-z,A-Z,0-9,\s)
  • numeric 确保只有数字键值
  • integer 确保只有整数键值
  • boolean 检查是否为PHP接受的布尔值,对于"1"、"true"、"on"和"yes"返回TRUE
  • float 检查是否为浮点值
  • valid_url 检查是否为有效的URL或子域
  • url_exists 检查URL是否存在且可访问
  • valid_ip 检查是否为有效的通用IP地址
  • valid_ipv4 检查是否为有效的IPv4地址
  • valid_ipv6 检查是否为有效的IPv6地址
  • valid_cc 检查是否为有效的信用卡号(使用MOD10校验和算法)
  • valid_name 检查是否为有效的人类姓名格式
  • contains,n 验证值是否包含在预定义的值集中
  • 包含列表,n 验证一个值是否包含在预定义的值集中。有效的值列表必须以分号分隔的列表格式提供(例如:value1;value2;value3;..;valuen)。如果发生验证错误,则不会透露有效的值列表(这意味着错误只会说输入无效,而不会向用户透露有效的值集)。
  • 不包含列表,n 验证一个值是否不包含在预定义的值集中。分号(;)分隔的列表不输出。更多信息请参阅上面的规则。
  • street_address 检查提供的字符串是否是一个可能的街道地址。1个数字,1个或多个空格,1个或多个字母
  • iban 检查有效的IBAN
  • min_numeric 确定提供的数值是否大于或等于特定值
  • max_numeric 确定提供的数值是否小于或等于特定值
  • date 确定提供的输入是否是有效的日期(ISO 8601)
  • starts 确保值以特定字符/字符集开头
  • phone_number 验证匹配以下示例的电话号码:555-555-5555 , 5555425555, 555 555 5555, 1(519) 555-4444, 1 (519) 555-4422, 1-555-555-5555
  • regex 您可以使用以下格式传递自定义正则表达式:'regex,/your-regex/'
  • valid_json_string 验证字符串是否是有效的JSON格式

可用过滤器

过滤器可以是任何返回字符串的PHP函数。如果存在一个PHP函数可以完成您想要过滤器完成的操作,则不需要创建自己的。

  • sanitize_string 删除脚本标签并编码HTML实体,类似于GUMP::xss_clean();
  • urlencode 编码URL实体
  • htmlencode 编码HTML实体
  • sanitize_email 从电子邮件地址中删除非法字符
  • sanitize_numbers 删除任何非数字字符
  • trim 从字符串的开始和结尾删除空格
  • base64_encode 对输入进行Base64编码
  • base64_decode 对输入进行Base64解码
  • sha1 使用安全的sha1算法加密输入
  • md5 对输入进行MD5编码
  • noise_words 从字符串中删除噪声词
  • json_encode 创建输入的JSON表示形式
  • json_decode 解码JSON字符串
  • rmpunctuation 从字符串中删除所有已知标点符号字符
  • basic_tags 从文本中删除所有布局导向的HTML标签,只留下基本标签
  • whole_number 确保提供的数值以整数形式表示

创建自己的验证器和过滤器

通过使用回调函数,添加自定义验证器和过滤器变得简单。

require("gump.class.php");

/* 
   Create a custom validation rule named "is_object".   
   The callback receives 3 arguments:
   The field to validate, the values being validated, and any parameters used in the validation rule.
   It should return a boolean value indicating whether the value is valid.
*/
GUMP::add_validator("is_object", function($field, $input, $param = NULL) {
    return is_object($input[$field]);
});

/* 
   Create a custom filter named "upper".
   The callback function receives two arguments:
   The value to filter, and any parameters used in the filter rule. It should returned the filtered value.
*/
GUMP::add_filter("upper", function($value, $params = NULL) {
    return strtoupper($value);
});

或者,您可以简单地创建一个扩展GUMP类的自定义类。

require("gump.class.php");

class MyClass extends GUMP
{
	public function filter_myfilter($value, $param = NULL)
	{
		...
	}

	public function validate_myvalidator($field, $input, $param = NULL)
	{
		...
	}

} // EOC

$validator = new MyClass();

$validated = $validator->validate($_POST, $rules);

请参阅examples/custom_validator.php以获取更多信息。

请记住创建具有正确参数类型和参数计数的公共方法。

  • 对于过滤器方法,在方法名前添加"filter_"。
  • 对于验证器方法,在方法名前添加"validate_"。

设置自定义字段名称

您可以使用GUMP::set_field_name($field, $readable_name)方法轻松覆盖表单字段名称,以在错误中使用更好的可读性,如下所示

$data = array(
	'str' => null
);

$rules = array(
	'str' => 'required'
);

GUMP::set_field_name("str", "Street");

$validated = GUMP::is_valid($data, $rules);

if($validated === true) {
	echo "Valid Street Address\n";
} else {
	print_r($validated);
}

验证文件字段

require "gump.class.php";

$is_valid = GUMP::is_valid(array_merge($_POST,$_FILES), array(
	'title' => 'required|alpha_numeric',
	'image' => 'required_file|extension,png;jpg'
));

if($is_valid === true) {
	// continue
} else {
	print_r($is_valid);
}

运行示例

  1. 打开您的终端
  2. cd [GUMP 目录]/examples
  3. php [文件].php

输出将取决于输入数据。

贡献者

待办事项

  • 货币验证器
  • 国家验证器
  • 位置坐标验证器
  • HTML验证器
  • 语言验证...判断一段文本是否为指定的语言
  • 验证垃圾邮件域名或IP。
  • 验证垃圾邮件电子邮件地址
  • 使用Askimet或类似工具验证垃圾邮件文本
  • 改进文档
  • 更多示例
  • W3C验证过滤器?
  • 一个与HTML tidy服务集成的过滤器?: http://infohound.net/tidy/
  • 添加Twitter & Facebook个人资料URL验证器: http://stackoverflow.com/questions/2845243/check-if-twitter-username-exists
  • 添加更多逻辑示例 - 登录表单、个人资料更新表单、博客帖子表单等。
  • 添加验证器以允许检查PHP $_FILES数组。
  • 允许一个可以检查主机机器上现有文件的验证器
  • 添加一个“为空”验证器检查
  • 检查数组是否有正计数(如果类型为数组)
  • 安全密码验证器