大希iii / validation
一个简单易用的输入验证库
1.0.1
2024-08-22 13:19 UTC
Requires
- php: >=8.3
Requires (Dev)
- phpunit/phpunit: ^11.3
README
PHP 输入验证库
这是一个简单的 PHP 输入验证库,用于确保 Web 应用程序中的数据完整性和安全性。该库提供了一系列验证各种类型输入的规则,并通过清理和验证来防止 XSS 和文件上传漏洞。
通过 composer 安装
composer require dachiiii/validation
用法
要验证输入数据,需要执行几个步骤,创建 FormValidationClass,设置规则,并进行验证。例如,如果您想验证添加产品表单,必须在您的项目中创建一个 常规类文件,并在其中编写规则,例如
<?php // your\namespace if necessarily use Validation\Validator; class ProductFormValidation extends Validator { protected array $categories = ['Books','Clothing','Software','Other']; protected array $mimes = ['image/png','image/jpeg']; public function __construct() { $this->initRules(); } private function initRules() { $this->rules['productName'] = "string|required|max:40"; $this->rules['productDescription'] = "string|min:80|max:3000"; $this->rules['productCategory'] = "string|required|in:categories"; $this->rules['productIsAvailable'] = "bool"; $this->rules['productPrice'] = "integer|min:0"; $this->rules['productImage'] = "file|mime:mimes"; } }
建议将这些文件放在该目录中,它可能看起来像这样
FormValidations/
├── AccountFormValidation.php
├── CommentFormValidation.php
└── ProductFormValidation.php
文件验证
$this->rules['file'] = "file";
此代码验证输入是否为文件,尽管这是正确的,但始终使用 mime:types 一起使用,因为没有使用 mime 类型进行验证,这意味着任何类型的文件都将通过验证,网站将容易受到文件上传漏洞的攻击。验证文件的最安全方法是
protected array $valid_mime_types = ['video/mp4','image/png','image/gif','image/jpeg',...]; ... $this->rules['file'] = "file|mime:valid_mime_types";
最终验证
$validator = new ProductFormValidation(); if ($validator->validate($to_validate, $validator->rules)) { // Validation Pass } else { // Validation Failed $errors = $validator->getErrors(); }