Advertisement
dimipan80

PIN Validation

Apr 28th, 2015
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.35 KB | None | 0 0
  1. <?php
  2. date_default_timezone_set('Europe/Sofia');
  3.  
  4. $name = trim($_GET['name']);
  5. $gender = trim($_GET['gender']);
  6. $pin = trim($_GET['pin']);
  7. if (!preg_match('/^[A-Z][a-z]+\s[A-Z][a-z]+$/', $name) || ($gender != 'male' && $gender != 'female') ||
  8.     !preg_match('/^\d{10}$/', $pin)
  9. ) {
  10.     die('<h2>Incorrect data</h2>');
  11. }
  12.  
  13. $sexDigit = (int)$pin[8];
  14. if (($gender == 'male' && ($sexDigit % 2) !== 0) ||
  15.     ($gender == 'female' && ($sexDigit % 2) === 0)
  16. ) {
  17.     die('<h2>Incorrect data</h2>');
  18. }
  19.  
  20. $year = substr($pin, 0, 2);
  21. $month = substr($pin, 2, 2);
  22. $dayOfMonth = substr($pin, 4, 2);
  23. if ((int)$month > 40) {
  24.     $year = '20' . $year;
  25.     $month = (int)$month - 40;
  26. } elseif ((int)$month > 20) {
  27.     $year = '18' . $year;
  28.     $month = (int)$month - 20;
  29. } else {
  30.     $year = '19' . $year;
  31. }
  32.  
  33. $dateStr = $month . '/' . $dayOfMonth . '/' . $year;
  34. $date = new DateTime($dateStr);
  35. if (!$date || ($date->format('n') != $month)) {
  36.     die('<h2>Incorrect data</h2>');
  37. }
  38.  
  39. $multipliers = [2, 4, 8, 5, 10, 9, 7, 3, 6];
  40. $totalSum = 0;
  41. foreach ($multipliers as $key => $multiplier) {
  42.     $digit = (int)$pin[$key];
  43.     $totalSum += ($digit * $multiplier);
  44. }
  45.  
  46. $totalSum = ($totalSum % 11) % 10;
  47. $checksum = (int)$pin[9];
  48. if ($checksum !== $totalSum) {
  49.     die('<h2>Incorrect data</h2>');
  50. }
  51.  
  52. $data = array('name' => $name, 'gender' => $gender, 'pin' => $pin);
  53. echo json_encode($data);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement