validator.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. class Validator {
  3. static $errors = true;
  4. static function check($arr, $on = false) {
  5. if ($on === false) {
  6. $on = $_REQUEST;
  7. }
  8. foreach ($arr as $value) {
  9. if (empty($on[$value])) {
  10. self::throwError('Data is missing', 900);
  11. }
  12. }
  13. }
  14. static function int($val) {
  15. $val = filter_var($val, FILTER_VALIDATE_INT);
  16. if ($val === false) {
  17. self::throwError('Invalid Integer', 901);
  18. }
  19. return $val;
  20. }
  21. static function str($val, $empty=false) {
  22. if (!is_string($val)) {
  23. self::throwError('Invalid String', 902);
  24. }
  25. $val = trim(htmlspecialchars($val));
  26. if(strlen($val) === 0 && !$empty) self::throwError('Empty String', 907);
  27. return $val;
  28. }
  29. static function bool($val) {
  30. $val = filter_var($val, FILTER_VALIDATE_BOOLEAN);
  31. return $val;
  32. }
  33. static function email($val) {
  34. $val = filter_var($val, FILTER_VALIDATE_EMAIL);
  35. if ($val === false) {
  36. self::throwError('Invalid Email', 903);
  37. }
  38. return $val;
  39. }
  40. static function url($val) {
  41. $val = filter_var($val, FILTER_VALIDATE_URL);
  42. if ($val === false) {
  43. self::throwError('Invalid URL', 904);
  44. }
  45. return $val;
  46. }
  47. static function file($val, $ext = false) {
  48. if (($val['error'] !== UPLOAD_ERR_OK) || !is_uploaded_file($val['tmp_name'])) {
  49. self::throwError('File upload error',905);
  50. }
  51. if ($ext) {
  52. $fileName = $val['name'];
  53. // $fileSize = $val['size'];
  54. $fileNameCmps = explode(".", $fileName);
  55. $fileExtension = strtolower(end($fileNameCmps));
  56. if (strcmp($ext, $fileExtension) !== 0) {
  57. self::throwError('Invalid file extension',906);
  58. }
  59. }
  60. return $val;
  61. }
  62. static function throwError($error = 'Error In Processing', $errorCode = 0) {
  63. if (self::$errors === true) {
  64. throw new Exception($error, $errorCode);
  65. }
  66. }
  67. }