Home > Enterprise >  PHP Unique random string generator
PHP Unique random string generator

Time:03-06

How to make a random string unique to the string in the column below?

enter image description here

<?php
$n=10;
function getName($n) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';

    for ($i = 0; $i < $n; $i  ) {
        $index = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }

    return $randomString;
}

echo getName($n);
?>

CodePudding user response:

<?php
    $n = 10;
    function getName($n) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $n; $i  ) {
            $index = rand(0, strlen($characters) - 1);
            $randomString .= $characters[$index];
        }
        return $randomString;
    }
    function getUniqueString($length, $dbConnection){
        $string = getName($length);
        $count  = $dbConnection->query("SELECT * FROM TABLE_NAME WHERE string='$string')")->num_rows;
        while($count != 0){
            $string = getName($length);
            $count  = $dbConnection->query("SELECT * FROM TABLE_NAME WHERE string='$string')")->num_rows;
        }
        return $string;
    }

    echo getUniqueString($n, $dbConnection);
?>

CodePudding user response:

You can use openssl_random_pseudo_bytes() or random_bytes() PHP fonction to generate random strings.

You can also rely on MySQL to generate uniq IDs :

INSERT INTO mytable (alphaID) VALUES (REPLACE( UUID(), '-', '' )); 
  • Related