PHP数据校验与完整性验证
PHP数据校验与完整性验证数据校验是保证数据质量的关键。PHP提供了多种校验机制来验证数据的完整性和一致性。今天说说PHP中的各种校验技术。最基本的校验是格式校验。PHP的filter_var可以验证常见的数据格式。phpclass DataValidator{private array $errors [];private array $validated [];public function validate(array $data, array $rules): bool{$this-errors [];$this-validated [];foreach ($rules as $field $ruleSet) {$value $data[$field] ?? null;$rules is_string($ruleSet) ? explode(|, $ruleSet) : $ruleSet;foreach ($rules as $rule) {$error $this-applyRule($field, $value, $rule);if ($error ! null) {$this-errors[$field][] $error;}}if (!isset($this-errors[$field])) {$this-validated[$field] $value;}}return empty($this-errors);}private function applyRule(string $field, mixed $value, string $rule): ?string{$params [];if (str_contains($rule, :)) {[$rule, $paramStr] explode(:, $rule, 2);$params explode(,, $paramStr);}if ($value null || $value ) {if ($rule required) {return {$field}是必填项;}return null;}return match ($rule) {email !filter_var($value, FILTER_VALIDATE_EMAIL) ? {$field}不是有效的邮箱 : null,url !filter_var($value, FILTER_VALIDATE_URL) ? {$field}不是有效的URL : null,ip !filter_var($value, FILTER_VALIDATE_IP) ? {$field}不是有效的IP : null,integer !filter_var($value, FILTER_VALIDATE_INT) ? {$field}必须是整数 : null,numeric !is_numeric($value) ? {$field}必须是数字 : null,boolean !in_array($value, [true, false, true, false, 0, 1, 0, 1], true) ? {$field}必须是布尔值 : null,min (float)$value (float)($params[0] ?? 0) ? {$field}不能小于{$params[0]} : null,max (float)$value (float)($params[0] ?? 0) ? {$field}不能大于{$params[0]} : null,min_length mb_strlen((string)$value) (int)($params[0] ?? 0) ? {$field}长度不能小于{$params[0]} : null,max_length mb_strlen((string)$value) (int)($params[0] ?? 0) ? {$field}长度不能大于{$params[0]} : null,regex !preg_match(/ . ($params[0] ?? ) . /, (string)$value) ? {$field}格式不正确 : null,in !in_array((string)$value, $params) ? {$field}不在允许的值范围内 : null,date !strtotime((string)$value) ? {$field}不是有效的日期 : null,json !json_decode((string)$value) ? {$field}不是有效的JSON : null,default null,};}public function getErrors(): array{return $this-errors;}public function getValidated(): array{return $this-validated;}}?数据完整性校验使用哈希函数。phpclass IntegrityChecker{public static function hashFile(string $path, string $algorithm sha256): string{return hash_file($algorithm, $path);}public static function hashData(string $data, string $algorithm sha256): string{return hash($algorithm, $data);}public static function verifyFile(string $path, string $expectedHash, string $algorithm sha256): bool{return hash_equals($expectedHash, self::hashFile($path, $algorithm));}public static function createManifest(string $dirPath): array{$manifest [];$iterator new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath));foreach ($iterator as $file) {if ($file-isFile()) {$relativePath str_replace($dirPath, , $file-getPathname());$manifest[$relativePath] self::hashFile($file-getPathname());}}return $manifest;}public static function checkManifest(string $dirPath, array $expected): array{$changes [];$current self::createManifest($dirPath);foreach ($expected as $path $hash) {if (!isset($current[$path])) {$changes[missing][] $path;} elseif ($current[$path] ! $hash) {$changes[modified][] $path;}}foreach ($current as $path $hash) {if (!isset($expected[$path])) {$changes[added][] $path;}}return $changes;}public static function signData(string $data, string $key): string{return hash_hmac(sha256, $data, $key);}public static function verifySignedData(string $data, string $signature, string $key): bool{return hash_equals(self::signData($data, $key), $signature);}}// 校验文件完整性$testFile /tmp/test_integrity.txt;file_put_contents($testFile, 测试数据);$hash IntegrityChecker::hashFile($testFile);echo 文件哈希: {$hash}\n;echo 验证通过: . (IntegrityChecker::verifyFile($testFile, $hash) ? 是 : 否) . \n;// 数据签名$data 重要数据;$key secret-key;$signature IntegrityChecker::signData($data, $key);echo 签名: {$signature}\n;echo 签名验证: . (IntegrityChecker::verifySignedData($data, $signature, $key) ? 通过 : 不通过) . \n;echo 篡改检测: . (IntegrityChecker::verifySignedData($data . x, $signature, $key) ? 通过 : 不通过) . \n;?数据验证的常见模式phpclass ValidatedRequest{private array $validated [];private array $errors [];public function __construct(array $data, array $rules){$validator new DataValidator();if ($validator-validate($data, $rules)) {$this-validated $validator-getValidated();} else {$this-errors $validator-getErrors();}}public function isValid(): bool{return empty($this-errors);}public function get(string $key, mixed $default null): mixed{return $this-validated[$key] ?? $default;}public function all(): array{return $this-validated;}public function errors(): array{return $this-errors;}public function fails(): bool{return !empty($this-errors);}}$request new ValidatedRequest([name 张三,email invalid-email,age 200,], [name required|min_length:2|max_length:50,email required|email,age required|numeric|min:1|max:150,]);if ($request-fails()) {echo 验证失败:\n;foreach ($request-errors() as $field $errors) {foreach ($errors as $error) {echo {$field}: {$error}\n;}}} else {echo 验证通过\n;print_r($request-all());}?数据校验是应用安全的第一道防线。输入验证、完整性校验、签名验证在不同层面上保护数据的安全。合理的校验策略可以防止大多数数据相关的安全问题和业务错误。