Validate Bulgarian ID number (EGN)
This function will allow you to verify if a given string matches the standard
for unique ID of Bulgarian citizen (EGN).
/**
* Check if the given parameter is valid ID of Bulgarian citizen (EGN).
* @author Samui Banti - https://samiwell.eu
* @param string $idNumber - A unique ID of Bulgarian citizen.
* @return boolian - TRUE if the ID is valid.
*/
function validateBulgarianID($idNumber)
{
$weights = [2,4,8,5,10,9,7,3,6];
if ( strlen($idNumber) != 10 ) {
return false;
}
$year = substr($idNumber,0,2);
$month = substr($idNumber,2,2);
$day = substr($idNumber,4,2);
if ($month > 40) {
if ( !checkdate($month-40, $day, $year+2000) ) {
return false;
}
} else {
if ($month > 20) {
if ( !checkdate($month-20, $day, $year+1800) ) {
return false;
}
} else {
if ( !checkdate($month, $day, $year+1900) ) {
return false;
}
}
}
$checksum = substr($idNumber,9,1);
$idNumberSum = 0;
for ( $i=0;$i<9;$i++ ) {
$idNumberSum += substr($idNumber,$i,1) * $weights[$i];
}
$valid_checksum = $idNumberSum % 11;
if ( $valid_checksum == 10 ) {
$valid_checksum = 0;
}
if ( $checksum == $valid_checksum ) {
return true;
}
return false;
}
The following method will allow you to get the citizen birth date from the ID:
/**
* Get the birthday date from given valid ID of Bulgarian citizen (EGN).
* @author Samui Banti - https://samiwell.eu
* @param string $idNumber - A unique ID of Bulgarian citizen.
* @return string $birthDay - The birth date in format YYYY-MM-DD
*/
function getBirthDayFromBulgarianID($idNumber)
{
$year = substr($idNumber, 0, 2);
$month = substr($idNumber, 2, 2);
$day = substr($idNumber, 4, 2);
if ($month > 40) {
$month -= 40;
$year += 2000;
} else if ($month > 20) {
$month -= 20;
$year += 1800;
} else {
$year += 1900;
}
$month = str_pad($month, 2, '0', STR_PAD_LEFT);
$day = str_pad($day, 2, '0', STR_PAD_LEFT);
$birthDay = "{$year}-{$month}-{$day}";
return $birthDay;
}