Validating a Portuguese tax number (NIF)
As I needed to build a tool to validate Portuguese tax numbers (NIF), here is the PHP function I wrote for that purpose.
/**
* Checks whether the structure of a Portuguese tax number (NIF) is valid
*
* @todo check that all characters are digits…
*
* Returns:
* – 0 if the number is valid
* – 1 if the number is invalid
* – 2 if the number has the wrong length
*
*
*/
function calcularNif($string_nif){
if(strlen($string_nif)==9){
$nif_temp=str_split($string_nif);
$soma_controlo=0;
$digito_controlo_calculado=0;
for($indice=0;$indice<8;$indice++){
$soma_controlo+=$nif_temp[$indice]*($indice+2);
}
$calculo_parcial=intval($soma_controlo/11);
$calculo_parcial2=11*$calculo_parcial;
$digito_controlo_calculado=$soma_controlo-$calculo_parcial2;
if($digito_controlo_calculado==10)
$digito_controlo_calculado=0;
if($digito_controlo_calculado==$nif_temp[8])
return 0; //Returns 0 if the number is valid
else
return 1; //Returns 1 if the number is invalid
}
return 2; // Returns 2 if the number has an invalid length
}
?>Note: Obviously, you use this code at your own risk and should check that it is correct. I do not have and do not accept any responsibility for its use or for any damage resulting from it.