Hi, I am looking for some example code that can help me to generate unique random string of numeric numbers in PHP Applications. I am hoping to resolve this issue with the help of tech developers working around & for this I have researched for many php questions & answers in various forums, but didn't get any satisfactory response. Hoping to get answer here.

Dani AI

Generated

For numeric-only unique keys you need to decide two things up front: how unguessable the value must be (just unique vs cryptographically secret) and how you will guarantee uniqueness at scale. As pointed out, pick the required length first — the space of possible values is 10^N for N digits, so collisions rise fast with short N. ’s time-based/hashed approach yields hex characters and depends on time-based entropy, so it isn’t a CSPRNG and is not recommended for unguessable IDs. (php.net)

Prefer PHP’s CSPRNG APIs (PHP 7+). For digit-only strings it’s easiest to build the string with random_int(0,9) in a loop; random_bytes() is the raw-byte alternative if you need bytes first. For older PHP you can fall back to openssl_random_pseudo_bytes() (check the “strong” flag). Example:

function generateNumericKey($length = 10) {
    $key = '';
    for ($i = 0; $i < $length; $i++) {
        $key .= random_int(0, 9);
    }
    return $key;
}

Use random_int() / random_bytes() for CSPRNG-grade randomness. (php.net)

Always enforce uniqueness at the storage layer (unique index/constraint) and handle the rare collision by retrying the insert a few times. Example (PDO):

$maxAttempts = 5; $attempt = 0;
do {
    $code = generateNumericKey(10);
    try {
        $stmt = $pdo->prepare('INSERT INTO codes (code) VALUES (:code)');
        $stmt->execute([':code' => $code]);
        $ok = true;
    } catch (PDOException $e) {
        if ($e->getCode() === '23000' || (isset($e->errorInfo[1]) && $e->errorInfo[1] == 1062)) {
            $ok = false; $attempt++;
        } else {
            throw $e;
        }
    }
} while (!$ok && $attempt < $maxAttempts);

Let the DB reject duplicates and retry (don’t rely on “generate then check” without a unique constraint). Database unique constraints/indexes are the correct mechanism to guarantee uniqueness. (postgresql.org)

Quick tips: choose N so 10^N is comfortably larger than your total expected keys; avoid rand()/mt_rand() for secrets; log and monitor duplicate rates and increase length if collisions appear.

Recommended Answers

All 2 Replies

Member Avatar for Member #120589

This is a help forum not a gimme code hangout. Show what you.ve done. Give more info as in the length etc

commented: This is a satisfying and suitable response. +11

Given below is the function I used to generate apikeys. May be you are searching for this. Please remove 'md5' if you dont want letters in the string. Also please try to give more info as like diafol mentioned above.

function generateApiKey() {
     return md5(uniqid(rand(), true));
   }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.