Advertisement
coasterka

03_PINValidation.php

Aug 27th, 2014
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.21 KB | None | 0 0
  1. <?php
  2.  
  3. $name = $_GET['name'];
  4. $gender = $_GET['gender'];
  5. $pin = $_GET['pin']; // 9912164756
  6.  
  7. $birthDate = substr($pin, 0, 6); // 991216
  8. $birthYear = substr($birthDate, 0, 2); // 99
  9. $birthMonth = substr($birthDate, 2, 2); // 12
  10. $birthDay = substr($birthDate, 4, 2); // 16
  11. $regionID = substr($pin, 6, 3); // 475
  12. $genderID = substr($regionID, 2, 1); // 5
  13. $checksum = substr($pin, 9, 1); // 6
  14.  
  15. $checksumDigits = str_split(substr($pin, 0, 9));
  16.  
  17. if (isValidName($name) && isValidGender($gender, $genderID) &&
  18.     isValidMonth($birthMonth) && isValidDay($birthDay) &&
  19.     isValidCheckSum($checksumDigits, $checksum) && isValidPinLength($pin)):
  20.     $result = new stdClass();
  21.     $result->name = $name;
  22.     $result->gender = $gender;
  23.     $result->pin = $pin;
  24.     echo json_encode($result);
  25. else:
  26.     echo "<h2>Incorrect data</h2>";
  27. endif;
  28.  
  29. function isValidPinLength($pin) {
  30.     $pinLength = strlen($pin);
  31.     if ($pinLength === 10):
  32.         return TRUE;
  33.     else:
  34.         return FALSE;
  35.     endif;
  36. }
  37.  
  38. function isValidName($name) {
  39.     $nameArr = preg_split('/\s+/', $name);
  40.     if (sizeof($nameArr) === 2):
  41.         return TRUE;
  42.     else:
  43.         return FALSE;
  44.     endif;
  45. }
  46.  
  47. function isValidMonth($month) {
  48.     if (($month >= 1 && $month <= 12) ||
  49.         ($month >= 21 && $month <= 32) ||
  50.         ($month >= 41 && $month <= 52)):
  51.         return TRUE;
  52.     else:
  53.         return FALSE;
  54.     endif;
  55. }
  56.  
  57. function isValidDay($day) {
  58.     if ($day >= 1 && $day <= 31):
  59.         return TRUE;
  60.     else:
  61.         return FALSE;
  62.     endif;
  63. }
  64.  
  65. function isValidGender($gender, $genderID) {
  66.     if (($gender === 'female' && $genderID % 2 === 1) ||
  67.         ($gender === 'male' && $genderID % 2 === 0)):
  68.         return TRUE;
  69.     else:
  70.         return FALSE;
  71.     endif;
  72. }
  73.  
  74. function isValidCheckSum ($digits, $checksum) {
  75.     $multipliers = array(2, 4, 8, 5, 10, 9, 7, 3, 6);
  76.     $result = 0;
  77.     $remainder = 0;
  78.     for($i = 0; $i < sizeof($digits); $i++):
  79.         $result += $digits[$i] * $multipliers[$i];
  80.     endfor;
  81.     $remainder = $result % 11;
  82.     if (($remainder == $checksum) ||
  83.         ($remainder == 10 && $checksum == 0)):
  84.         return TRUE;
  85.     else:
  86.         return FALSE;
  87.     endif;
  88. }
  89.  
  90. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement