English · Italiano
A library to generate, validate and decode the Italian fiscal code (codice fiscale) of natural persons. It works for people born in Italy and for people born abroad.
- Pure PHP, from 7.4 on, with no dependencies. It works with Laravel, Yii2, Symfony, CodeIgniter, Slim or plain PHP.
- It includes the ANPR historical register: ~9,850 cadastral codes of Italian municipalities, including those that were abolished or renamed, with their validity periods. On top of that, ~220 foreign states, including former ones such as the USSR, Yugoslavia, Czechoslovakia and East Germany.
- It handles omocodia strictly (DM 23/12/1976), the century of birth, accented names and municipalities with the same name.
- It is easy to port to other languages: the specification is in docs/ALGORITHM.md, the data is JSON and the test vectors, shared between implementations, are in tests/vectors.json.
composer require pierdolabs/codice-fiscale
To also use suggestNames() (most likely first names and surnames) you need the separate data package, about 24 MB:
composer require pierdolabs/codice-fiscale-names
Without that package every other function keeps working; suggestNames() throws a RuntimeException that explains what to install, and Names::isAvailable() tells whether the data is there.
use PierdoLabs\CodiceFiscale\CodiceFiscale; use PierdoLabs\CodiceFiscale\InvalidCodiceFiscaleException; // Generation: the place is given by name or by cadastral code CodiceFiscale::generate('Rossi', 'Mario', '1980-01-01', 'M', 'Roma'); // RSSMRA80A01H501U CodiceFiscale::generate('Müller', 'Anna', '1990-05-20', 'F', 'Germania'); // MLLNNA90E60Z112E CodiceFiscale::generate('Rossi', 'Mario', '1980-01-01', 'M', 'San Teodoro', 'NU'); // the province tells municipalities with the same name apart CodiceFiscale::generate('Rossi', 'Mario', new DateTime('1980-01-01'), 'M', 'H501'); // Validation CodiceFiscale::isValid('RSSMRA80A01H501U'); // true CodiceFiscale::validate('RSSMRA80A01H501X'); // ['CHECK_CHAR' => 'Carattere di controllo errato'] // Decoding $d = CodiceFiscale::decode('DLCFNC01L46H50MJ'); $d->gender; // 'F' $d->birthDate->format('Y-m-d'); // '2001-07-06' $d->place->name; // 'ROMA' $d->place->province; // 'RM' $d->isForeignBorn(); // false $d->omocodiaLevel; // 1 $d->surnameCode; // 'DLC' $d->nameCode; // 'FNC' $d->age(); // age in years $d->toArray(); // array, ready for JSON try { CodiceFiscale::decode('XXXXXXXXXXXXXXXX'); } catch (InvalidCodiceFiscaleException $e) { $e->getErrors(); // ['CHECK_CHAR' => '...', ...] } // First name and surname cannot be recovered from the code, only checked CodiceFiscale::matchesName('RSSMRA80A01H501U', 'Rossi', 'Mario'); // true // Omocodia CodiceFiscale::omocodes('RSSMRA80A01H501U'); // the 7 omocodic variants CodiceFiscale::baseCode('DLCFNC01L46H50MJ'); // DLCFNC01L46H501R: non-omocodic code, with the check character recomputed
use PierdoLabs\CodiceFiscale\Places; Places::byCode('A952'); // BOLZANO (BZ), alias BOZEN Places::byCode('A952', new DateTime('1925-01-01')); // BOLZANO (TN): the period valid on that date Places::all('H501'); // every period Places::search('Bozen'); // [Place A952] Places::search('Germany'); // [Place Z112]: English names are searched too Places::search('San Teodoro'); // 2 results (ME, NU) Places::search('Georgia', 'EE'); // foreign states only
// To check cadastral codes against your own database instead of the bundled register CodiceFiscale::setPlaceValidator(function (string $code, DateTimeImmutable $birthDate): bool { return MyMunicipalities::exists($code); }); // To translate the error messages (Italian by default) CodiceFiscale::setMessages([ CodiceFiscale::ERR_EMPTY => 'Fiscal code is missing', CodiceFiscale::ERR_LENGTH => 'The fiscal code must be 16 characters long', CodiceFiscale::ERR_FORMAT => 'The fiscal code contains invalid characters', CodiceFiscale::ERR_OMOCODIA => 'Invalid omocodia substitution', CodiceFiscale::ERR_CHECK_CHAR => 'Invalid check character', CodiceFiscale::ERR_SURNAME => 'Invalid surname code', CodiceFiscale::ERR_NAME => 'Invalid first name code', CodiceFiscale::ERR_DATE => 'Invalid date of birth', CodiceFiscale::ERR_PLACE => 'Unknown place of birth code', ]); // To use a different places register (same format as data/places.json) Places::setDataFile('/path/places.json');
// Inline validation $request->validate([ 'codice_fiscale' => ['required', function ($attr, $value, $fail) { if (!\PierdoLabs\CodiceFiscale\CodiceFiscale::isValid($value)) { $fail('The fiscal code is not valid.'); } }], ]);
To reuse the rule, put it in a class (php artisan make:rule CodiceFiscaleRule):
use Closure; use Illuminate\Contracts\Validation\ValidationRule; use PierdoLabs\CodiceFiscale\CodiceFiscale; class CodiceFiscaleRule implements ValidationRule { public function validate(string $attribute, mixed $value, Closure $fail): void { foreach (CodiceFiscale::validate((string) $value) as $message) { $fail($message); } } }
public function rules() { return [ ['codice_fiscale', 'required'], ['codice_fiscale', function ($attribute) { foreach (\PierdoLabs\CodiceFiscale\CodiceFiscale::validate($this->$attribute) as $msg) { $this->addError($attribute, $msg); } }], ]; }
use Symfony\Component\Validator\Constraints\Callback; use Symfony\Component\Validator\Context\ExecutionContextInterface; #[Callback] public function validateCf(ExecutionContextInterface $context): void { foreach (\PierdoLabs\CodiceFiscale\CodiceFiscale::validate($this->codiceFiscale) as $msg) { $context->buildViolation($msg)->atPath('codiceFiscale')->addViolation(); } }
| Code | Meaning |
|---|---|
EMPTY |
empty string |
LENGTH |
length other than 16 |
FORMAT |
characters not allowed |
OMOCODIA |
omocodic substitutions out of order |
CHECK_CHAR |
wrong check character |
SURNAME / NAME |
invalid triplet (e.g. AXA) |
DATE |
date that does not exist (e.g. 30 February, 29 February in a non-leap year) |
PLACE |
unknown cadastral code |
- First name and surname cannot be recovered from the code: the code keeps only 3 letters of each. You get the codes (
surnameCode,nameCode) and you can check a name withmatchesName(). - Century: the year has only 2 digits. The most recent century that does not give a future date is chosen, then the place is checked to have existed on that date. Example:
25with a municipality abolished in 1927 gives 1925. For people aged 100 or more the century can be wrong. For tests, pass the reference date as the second argument ofdecode()andvalidate(). - The 11-digit temporary fiscal code (legal persons, or people waiting for a definitive code) is not supported.
Spaces, apostrophes and hyphens are ignored, so Maria Grazia and Mariagrazia give the same code (MGR). In practice:
| Input | Code |
|---|---|
Maria Grazia / Mariagrazia |
MGR |
Maria |
MRA (different: the second name counts) |
Grazia Maria |
GZM (the order counts too) |
Anna Maria / Ana Maria |
NMR |
Gian Luca / Gianluca |
GLC |
Esposito Russo / Esposito |
SPS (the second surname often makes no difference) |
De Luca |
DLC |
So matchesName() cannot tell Esposito from Esposito Russo. Full examples: composer examples (examples/esempi.php).
The fiscal code does not contain the first name and surname. suggestNames() returns a statistical ranking of the names compatible with its triplets, filtered by the sex stated in the code:
CodiceFiscale::suggestNames('SPSMGR78C55F839X', 5); // [ // 'surnames' => [['name' => 'Esposito', 'score' => 0.76], ['name' => 'Sposito', 'score' => 0.02], ...], // 'names' => [['name' => 'Maria Grazia', 'score' => 0.72], ['name' => 'Margaret', 'score' => 0.08], ...], // ]
- Country of birth. Names are weighted on the country of birth: Italy, or the foreign state given in the code. For a Spaniard
GRC JLSgivesGarcíaandJosé Luis, for a RomanianPPSgivesPopescu. If there is no data for that country, world counts are used. - Province of birth (people born in Italy only). For people born in Italy the province of birth counts too, as much as the national data. The same triplet
MNTgivesMontemurroin Matera andMontanariin Ravenna,RSSgivesRussoin Palermo andRossiin Milan. For people born abroad the code gives only the state, so there is no province to weigh. - How the score is computed.
- Each source contributes the share of the name within the triplet: Wikidata for the country with weight 1, official statistics for the country with weight 2, Wikidata for the province of birth with weight 1, open data from the municipalities of the province with weight 2, world Wikidata with weight 0.1.
- Official statistics weigh less (0.5) for people born before their coverage starts: Italy 1999, United Kingdom 1996, Austria 1984.
- The score is the share of the name among those in the dictionary, not a certain probability.
- Equivalent spellings. Spellings that are the same for the code become a single entry:
Mariagraziacounts asMaria Grazia,HanspeterasHans-Peter. - Dictionary. The data is in the separate package
pierdolabs/codice-fiscale-names, folderdata/:<ISO3>.tsvfor each country,IT-<code>.tsvfor each Italian province andWLD.tsvfor the world. About 330 files, 24 MB in total. Only the files needed (world, country and province) are loaded, on the first call. It is rebuilt withcomposer build-names, which writes to../codice-fiscale-names/dataor to the folder in theCF_NAMES_DIRvariable (needs ext-zip; the first full download takes a few minutes, then the files stay cached for 7 days). - Limitations. Wikidata mostly lists well-known people. For countries without official statistics (most of them, including the Netherlands and Denmark) the estimate is therefore less reliable.
| Source | Country | Data | Licence |
|---|---|---|---|
| Wikidata (via QLever) | all | people by first name (with sex) and surname, by citizenship and, in Italy, by province of the municipality of birth | CC0 |
| ISTAT, Contanomi | Italy | 50 most common names by sex among births, since 1999 | CC BY 4.0, © ISTAT |
| Municipal open data (Vittorio Veneto, Unione Valle Savio, Bergamo, Brescia, Matera, Lecce and 60 municipalities on the Maggioli platform, including Pescara, Taranto, Piacenza, Olbia, Lamezia Terme) | Italy | names of births and residents, surnames of residents with Italian citizenship | CC0 / CC BY 4.0, © the respective municipalities |
| INSEE, Fichier des prénoms | France | births by name since 1900 | Licence Ouverte 2.0, Source : Insee |
| INE, nombres y apellidos | Spain | population by name | Fuente: INE (www.ine.es) |
| Statbel | Belgium | population by name and 10,000 most common surnames | CC BY 4.0, Source: Statbel |
| BFS/OFS, STATPOP | Switzerland | population by first name and surname | Source: FSO – STATPOP |
| SSB | Norway | births by name since 1880, and surnames | CC BY 4.0, Statistics Norway |
| SCB | Sweden | population by name in use and surname (2020) | CC BY 4.0, Statistics Sweden |
| ONS | England and Wales | births by name since 1996 | Open Government Licence v3.0, Source: ONS |
| Statistik Austria | Austria | every name given to births since 1984 | Statistik Austria terms of use, "Source: STATISTIK AUSTRIA; data processed" |
| UCI Gender by Name (DOI 10.24432/C55G7X) | USA, Canada, Australia | births by name: SSA 1880–2019, British Columbia, Australia | CC BY 4.0 |
Excluded sources:
- SSA and Census (USA): they block automated downloads. SSA names still arrive through UCI, while US surnames come from Wikidata only.
- INE surnames (Spain): only available as binary
.xls. - DST (Denmark), CBS and Meertens (Netherlands): no bulk downloads.
- Datasets derived from leaks or scraping: not used, for legal reasons (see the next section).
Many datasets come from the leak of 533 million Facebook profiles, collected in 2019 and published in 2021, or from other social network scraping:
philipperemy/name-dataset;- several Kaggle datasets, for example
erpel1/forenames-and-surnames…andjojo1000/facebook-last-names.
They are personal data collected without a legal basis (GDPR, Articles 5, 6 and 14). The licence of the code (Apache, MIT) does not make using the data lawful, and even aggregated counts keep their unlawful origin. The library only uses public sources with an open licence.
Measured with composer bench (20,000 iterations, real and omocodic codes):
| Operation | PHP 8.2 (Windows, XAMPP) | PHP 7.4 (Docker Linux) |
|---|---|---|
generate (place by code) |
~7 µs | ~5.5 µs |
generate (place by name) |
~9 µs | ~6.5 µs |
isValid / validate |
~10–11 µs | ~6.5–7 µs |
decode |
~11 µs | ~7 µs |
matchesName |
~1.2 µs | ~1.1 µs |
Places::byCode |
~0.8 µs | ~0.4 µs |
suggestNames (first load of world + country: ~27 ms, ~14 MB) |
~350 µs | n/a |
| First load of the register (once per process) | ~15 ms, ~8 MB | ~126 ms*, ~12 MB |
| First name index (only when searching by name) | ~14 ms, +3 MB | ~30 ms, +5 MB |
* slowed down by the Docker volume mounted from Windows.
In practice, about 100,000 validations per second on one core. The main cost is the first load of places.json. With PHP-FPM it happens once per request; for bulk use a single long-running process is better, for example a worker or a batch command.
composer update-data # downloads the ANPR data and rebuilds data/places.json (needs ext-zip)Former states missing from ANPR are added by hand in data/stati-cessati.csv.
composer install
composer testRead the contributing guide and the code of conduct. For questions use Discussions; for vulnerabilities follow the security policy. Changes in each version are in the CHANGELOG.
MIT