Passport validation :: check digit example

 
<?php
 
    function calcCheckDigit($inputCode)
    {
        $btArray = str_split($inputCode);
        $total = 0;
 
        for ($index = 0; $index < sizeof($btArray); $index++) {
            $btChr = ord($btArray[$index]);
 
            if ($btChr == 60) {
                //convert spacer char < to 0
                $btArray[$index] = 0;
            } else if ($btChr >= 65) {
                //convert letters A-Z to 10-35
                $btArray[$index] = $btChr - 55;
            } else {
                //take numbers literally
                $btArray[$index] = $btChr - 48;
            }
 
            switch ($index % 3) {
                case 0:
                    $btArray[$index] *= 7;
                    break;
                case 1:
                    $btArray[$index] *= 3;
                    break;
                case 2:
                    $btArray[$index] *= 1;
                    break;
            }
 
            $total += $btArray[$index];
        }
 
        return (int) $total % 10;
    }
 
	$mrz2 = '7553279419RUS8712242M2104131>>>>>>>>>>>>>>02';
 
	// check the document number vs its check digit
	$documentNumber = substr($mrz2, 0, 9);
        $documentNumberCheckDigit = (int) substr($mrz2, 9, 1);
 
        if ($documentNumberCheckDigit != calcCheckDigit($documentNumber)) {
		echo "document number incorrect.\n";
        }
 
	// check the DOB vs its check digit
	$dob = substr($mrz2, 13, 6);
	$dobCheckDigit = (int) substr($mrz2, 19, 1);
 
        if ($dobCheckDigit != calcCheckDigit($dob)) {
		echo "DOB incorrect.\n";
        }
 
	// check the DateOfExpiry vs its check digit
	$dateOfExpiry = substr($mrz2, 21, 6);
	$dateOfExpiryCheckDigit = (int) substr($mrz2, 27, 1);
 
        if ($dateOfExpiryCheckDigit != calcCheckDigit($dateOfExpiry)) {
		echo "Date Of Expiry incorrect.\n";
        }
 
 
	// check the optional data field vs its check digit
	$optionalData = substr($mrz2, 28, 14);
 
        if ($optionalData != str_repeat(chr(60),14)) {
 
		$optionalDataCheckDigit = (int) substr($mrz2, 42, 1);
                if ($optionalDataCheckDigit != self::calcCheckDigit($optionalData)) {
			echo "Optional data incorrect.\n";
                }
        }
 
	//positions 1 to 10, 14 to 20, and 22 to 43
        $wholeLine = substr($mrz2, 0, 10) . substr($mrz2, 13, 7) . substr($mrz2, 21, 22);
	$wholeLineCheckDigit = (int) substr($mrz2, 43, 1);
 
	if ($wholeLineCheckDigit != self::calcCheckDigit($wholeLine)) {
			echo "Whole line incorrect.\n";
	}

Leave a Reply