Panoramica

Questa sezione mostra come costruire un semplice sito PHP che genera il codice fiscale italiano a partire da: nome, cognome, data di nascita, sesso e codice catastale del Comune.

Nota: l’esattezza dipende dal codice catastale del Comune (serve una tabella aggiornata). L’esempio qui sotto include un dizionario minimo e una struttura estendibile.

1) Regole base (in sintesi)

2) Implementazione PHP dell’algoritmo

<?php

function cf_normalize(string $s): string {
    $s = strtoupper(trim($s));
    $s = preg_replace('/\s+/', '', $s);
    $map = [
        'À'=>'A','Á'=>'A','Â'=>'A','Ã'=>'A','Ä'=>'A','Å'=>'A',
        'È'=>'E','É'=>'E','Ê'=>'E','Ë'=>'E',
        'Ì'=>'I','Í'=>'I','Î'=>'I','Ï'=>'I',
        'Ò'=>'O','Ó'=>'O','Ô'=>'O','Õ'=>'O','Ö'=>'O',
        'Ù'=>'U','Ú'=>'U','Û'=>'U','Ü'=>'U',
        'Ç'=>'C'
    ];
    $s = strtr($s, $map);
    $s = preg_replace('/[^A-Z]/', '', $s);
    return $s;
}

function cf_extract_letters(string $s): array {
    $s = cf_normalize($s);
    $consonants = preg_replace('/[AEIOU]/', '', $s);
    $vowels = preg_replace('/[^AEIOU]/', '', $s);
    return [$consonants, $vowels];
}

function cf_code_surname(string $surname): string {
    [$c, $v] = cf_extract_letters($surname);
    $code = $c . $v . 'XXX';
    return substr($code, 0, 3);
}

function cf_code_name(string $name): string {
    [$c, $v] = cf_extract_letters($name);
    if (strlen($c) >= 4) {
        $code = $c[0] . $c[2] . $c[3];
        return $code;
    }
    $code = $c . $v . 'XXX';
    return substr($code, 0, 3);
}

function cf_code_date(string $dateYmd, string $sex): string {
    $dt = DateTime::createFromFormat('Y-m-d', $dateYmd);
    if (!$dt) {
        throw new InvalidArgumentException('Data non valida');
    }

    $year = $dt->format('y');
    $monthNum = (int) $dt->format('n');
    $day = (int) $dt->format('j');

    $months = [1=>'A',2=>'B',3=>'C',4=>'D',5=>'E',6=>'H',7=>'L',8=>'M',9=>'P',10=>'R',11=>'S',12=>'T'];
    $month = $months[$monthNum] ?? null;
    if (!$month) {
        throw new InvalidArgumentException('Mese non valido');
    }

    $sex = strtoupper(trim($sex));
    if ($sex === 'F') {
        $day += 40;
    } elseif ($sex !== 'M') {
        throw new InvalidArgumentException('Sesso non valido');
    }

    return $year . $month . str_pad((string)$day, 2, '0', STR_PAD_LEFT);
}

function cf_control_char(string $partial15): string {
    $partial15 = strtoupper($partial15);
    if (!preg_match('/^[A-Z0-9]{15}$/', $partial15)) {
        throw new InvalidArgumentException('Stringa base non valida');
    }

    $odd = [
        '0'=>1,'1'=>0,'2'=>5,'3'=>7,'4'=>9,'5'=>13,'6'=>15,'7'=>17,'8'=>19,'9'=>21,
        'A'=>1,'B'=>0,'C'=>5,'D'=>7,'E'=>9,'F'=>13,'G'=>15,'H'=>17,'I'=>19,'J'=>21,
        'K'=>2,'L'=>4,'M'=>18,'N'=>20,'O'=>11,'P'=>3,'Q'=>6,'R'=>8,'S'=>12,'T'=>14,
        'U'=>16,'V'=>10,'W'=>22,'X'=>25,'Y'=>24,'Z'=>23,
    ];

    $even = [
        '0'=>0,'1'=>1,'2'=>2,'3'=>3,'4'=>4,'5'=>5,'6'=>6,'7'=>7,'8'=>8,'9'=>9,
        'A'=>0,'B'=>1,'C'=>2,'D'=>3,'E'=>4,'F'=>5,'G'=>6,'H'=>7,'I'=>8,'J'=>9,
        'K'=>10,'L'=>11,'M'=>12,'N'=>13,'O'=>14,'P'=>15,'Q'=>16,'R'=>17,'S'=>18,'T'=>19,
        'U'=>20,'V'=>21,'W'=>22,'X'=>23,'Y'=>24,'Z'=>25,
    ];

    $sum = 0;
    for ($i = 0; $i < 15; $i++) {
        $ch = $partial15[$i];
        $pos = $i + 1;
        $sum += ($pos % 2 === 1) ? ($odd[$ch] ?? 0) : ($even[$ch] ?? 0);
    }

    $rest = $sum % 26;
    return chr(ord('A') + $rest);
}

function cf_generate(string $surname, string $name, string $dateYmd, string $sex, string $comuneCode): string {
    $comuneCode = strtoupper(trim($comuneCode));
    if (!preg_match('/^[A-Z0-9]{4}$/', $comuneCode)) {
        throw new InvalidArgumentException('Codice comune non valido');
    }

    $partial = cf_code_surname($surname)
        . cf_code_name($name)
        . cf_code_date($dateYmd, $sex)
        . $comuneCode;

    return $partial . cf_control_char($partial);
}

3) Mini-sito: form + output (index.php)

Questo esempio genera il codice fiscale e mostra un messaggio di errore se i dati non sono validi.

<?php
require_once __DIR__ . '/config.php';

$error = null;
$result = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $surname = $_POST['surname'] ?? '';
        $name = $_POST['name'] ?? '';
        $birth = $_POST['birth'] ?? '';
        $sex = $_POST['sex'] ?? '';
        $comune = $_POST['comune'] ?? '';

        $result = cf_generate($surname, $name, $birth, $sex, $comune);
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}
?>
<!doctype html>
<html lang="it">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Generatore codice fiscale (demo)</title>
  <link rel="stylesheet" href="assets/css/styles.css">
</head>
<body>
  <main class="section">
    <h1>Generatore codice fiscale (demo)</h1>

    <?php if ($error): ?>
      <div class="flash error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <?php if ($result): ?>
      <div class="flash success"><strong>Codice fiscale:</strong> <?php echo htmlspecialchars($result); ?></div>
    <?php endif; ?>

    <form method="post" class="contact-form" style="max-width:560px; margin: 0 auto;">
      <div class="field"><label>Cognome</label><input name="surname" required></div>
      <div class="field"><label>Nome</label><input name="name" required></div>
      <div class="field"><label>Data di nascita (YYYY-MM-DD)</label><input name="birth" type="date" required></div>
      <div class="field"><label>Sesso</label>
        <select name="sex" required>
          <option value="M">M</option>
          <option value="F">F</option>
        </select>
      </div>
      <div class="field"><label>Codice Comune (es. H501)</label><input name="comune" required></div>
      <button class="btn btn-primary" type="submit">Genera</button>
    </form>

    <p class="muted" style="max-width: 780px; margin: 18px auto 0;">Per produzione: integra una tabella completa dei codici catastali (Comune/Stato estero) e gestisci i casi particolari (omocodia, nomi composti, ecc.).</p>
  </main>
</body>
</html>

4) Dettagli da non dimenticare in produzione

Keyword: codice fiscale php, generatore codice fiscale, algoritmo codice fiscale, php

Domande frequenti

Perché serve il codice catastale del Comune?

Perché il codice fiscale include 4 caratteri che identificano luogo di nascita (Comune o Stato estero).

Questo esempio gestisce omocodia?

No, è un esempio didattico “base”. Se serve, posso estendere l’algoritmo con gestione omocodia e tabella codici completa.

Collegamenti interni