DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Lucian has posted 4 posts at DZone. View Full User Profile

Generare CNP

04.18.2009
| 1219 views |
  • submit to reddit
        // Generare CNP

<?php

   /**
     * Generare CNP ptr anumiti parametri varsta-sex-rezident
     * 
     * @example generareCnp(1,19)
     * @param mixed $sex 1-Masculin 2-Fem 9
     * @param mixed $varsta Varsta cuprinsa intre 0 si 209 ani
     * @param rezident optional, true|false, implicit false
     * @return cnp Cnp aleator valid
     */
    function generareCnp($sex,$varsta,$rezident=false) {
        $errorMsg   = 'EROARE';
        $sirCiudat  ='279146358279';
        $strain     = ($sex==9) ? true:false;
        $sexVector =array('1','2','9'); //ptr amuzament
        //Verificarile datelor
        if(!in_array($sex,$sexVector)) {
             return $errorMsg;
        }
        if (!is_bool($rezident)) {
             return $errorMsg;
        }
        $an=date(Y)-$varsta;
        // Daca s-a nascut inainte de 1900 $sex = 3 sau 4
        if ( $an < 1900 && !$rezident && !$strain) $sex = $sex + 2;
        // Daca s-a nascut dupa 2000 $sex = 5 sau 6  
        if ( $an > 2000 && !$rezident && !$strain)  $sex = $sex + 4; 
        //daca este rezident 
        if ($rezident) $sex = $sex+6;
        $luna=rand(1,12);
        $zi = rand(1,31);
        //daca este un copil care s-a nascut anul acesta atunci avem grija ca data generata sa nu fie mai mare decat data de azi
        if ($an == date('Y')) { 
            $luna = rand(1,date('m'));
            $ziua = rand(1,date('d'));
        }

        $date = new DateTime($an.'-'.$luna.'-'.$zi);
        
        $judet=rand(1,52);
        $judet=($judet<10) ? '0'.$judet : $judet;
        $control = rand(1,999);
        if ($control<10) { 
            $control='00'.$control; 
        }
        else if ($control<100) {
            $control='0'.$control;
        }
        $cnp =  $sex . $date->format("ymd") . $judet.$control;
        $suma=0;
        for($i=0;$i<=11;$i++) {
            $suma+=$sirCiudat[$i]*$cnp[$i];
        }
        $rest = $suma%11;
        $cifraControl = ($rest==10) ? 1 : $rest;
        $cnp.=$cifraControl;
        if (strlen($cnp)!=13 ) {
             return $errorMsg;
        }
        
        else return $cnp;
        
    }


    for($i=0;$i<100;$i++) {
    echo generareCnp(rand(1,2),rand(0,209))."\n";
    }
    
?>