Created
December 20, 2012 14:17
-
-
Save tubalmartin/4345529 to your computer and use it in GitHub Desktop.
Validación NIF de personas jurídicas y entidades en general (ESPAÑA)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Valida NIF de personas jurídicas y entidades en general | |
* | |
* @param string $nif NIF to check | |
* | |
* @return bool returns true on success false otherwise | |
*/ | |
function nifEntity($nif) | |
{ | |
$nif = strtoupper(str_replace("-", "", trim($nif))); | |
if (preg_match("/^[ABCDEFGHJNPQRSUVW]{1}[0-9]{7}[0-9A-Z]{1}/", $nif)) | |
{ | |
$nif_codes = 'JABCDEFGHI'; | |
$sum = (string) getNifSum($nif); | |
$n = (10 - substr($sum, -1)) % 10; | |
if (strpos('ABCDEFGHJUV', $nif[0]) !== FALSE) | |
{ | |
// Numerico | |
return ($nif[8] == $n); | |
} | |
else if (strpos('PQRSNW', $nif[0]) !== FALSE) | |
{ | |
// Letras | |
return ($nif[8] == $nif_codes[$n]); | |
} | |
} | |
return FALSE; | |
} | |
// Función auxiliar usada para CIFs y NIFs especiales | |
function getNifSum($nif) | |
{ | |
$sum = $nif[2] + $nif[4] + $nif[6]; | |
for ($i = 1; $i < 8; $i += 2) | |
{ | |
$tmp = (string) (2 * $nif[$i]); | |
$tmp = $tmp[0] + ((strlen($tmp) > 1) ? $tmp[1] : 0); | |
$sum += $tmp; | |
} | |
return $sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment