Une chaine aléatoire et unique ... ça n'existe pas dans l'absolue, mais on peux s'en approcher et réduire fortement les chances d'avoir un doublon un jours.
La 1er fonction toute simple de PHP est uniqid(); qui génère une chaine basé sur la date.
On peux ajouté plus de complexité avec les paramètres complémentaires : uniqid('H', 10);
<?php
function random_str($nbr)
{
$str = "";
$chaine = "abcdefghijklmnpqrstuvwxy";
srand((double)microtime()*1000);
for($i=0; $i<$nbr; $i++) {
$str .= $chaine[rand()%strlen($chaine)];
}
return $str;
}
// Exemple d'un appel avec 12 caractères
$str = random_str(12);
?>
<?php
function random_str($nbr)
{
$str = "";
$chaine = "abcdefghijklmnpqrstuvwxy";
$nb_chars = strlen($chaine);
for($i=0; $i<$nbr; $i++)
{
$str .= $chaine[ rand(0, ($nb_chars-1)) ];
}
return $str;
}
// Exemple d'un appel avec 12 caractères
$str = random_str(12);
?>
Un troisième exemple qui cette-fois génère une chaine aléatoire unique un peux plus complexe :
<?php
function random_str()
{
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );
}
// Utilisation
$str = random_str();
?>