To answer this question specifically, two problems:

  1. $randstring is not in scope when you echo it.
  2. The characters are not getting concatenated together in the loop.

Here's a code snippet with the corrections:

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';

    for (i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }

    return $randomString;
}

Output the random string with the call below:

// Echo the random string.
echo generateRandomString();

// Optionally, you can give it a desired string length.
echo generateRandomString(64);

Please note that previous version of this answer used rand() instead of random_int() and therefore generated predictable random strings. So it was changed to be more secure, following advice from this answer.

Answer from Stephen Watkins on Stack Overflow
๐ŸŒ
W3Docs
w3docs.com โ€บ php
How to Generate a Random String with PHP
This tutorial includes several methods of generating a unique, random, alpha-numeric string with PHP. Follow the examples below, it will be easily done.
๐ŸŒ
w3tutorials
w3tutorials.net โ€บ blog โ€บ how-to-create-a-random-string-using-php
How to Generate a Random String in PHP: Step-by-Step Logic Guide for Variable Lengths โ€” w3tutorials.net
This guide will walk you through step-by-step methods to generate random strings of variable lengths, explaining the logic behind each approach, their use cases, and best practices to avoid common pitfalls. Whether you need a quick non-secure string for trivial tasks or a cryptographically secure token for user authentication, weโ€™ve got you covered. ... Basic familiarity with PHP syntax (functions, loops, arrays).
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.random-bytes.php
PHP: random_bytes - Manual
Generates a string containing uniformly selected random bytes with the requested length.
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ func_math_rand.asp
PHP rand() Function
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
๐ŸŒ
BackEndTea
backendtea.com โ€บ post โ€บ php-random
How to create a random string in PHP | BackEndTea
July 31, 2024 - The Randomizer class (introduced in PHP 8.2) is arguably the best way in OOP PHP to use randomness, and should be used whenever possible. It comes with 2 methods for creating random strings.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ program-to-generate-random-string-in-php
Program to generate random string in PHP - GeeksforGeeks
July 18, 2024 - Convert random bytes to ASCII values, then map these to characters from a predefined set, ensuring the random string meets the specified length. ... <?php function generateRandomString($length) { $characters = '0123456789abcdefghijklmnopqrs...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ generating-random-string-using-php
Generating Random String Using PHP - GeeksforGeeks
July 11, 2025 - The uniqid() function generates a unique string based on the current time in microseconds, optionally adding more entropy for uniqueness. Itโ€™s not cryptographically secure but useful for generating unique identifiers quickly in non-critical ...
Find elsewhere
๐ŸŒ
Oirp
rada.oirp.lu โ€บ wrtdsrv โ€บ 09ce2d-generate-random-string-in-php-w3schools
generate random string in php w3schools
The safer way is: (0|Math.random()*9e6).toString(36) This will generate a random string of 4 or 5 characters, always diferent. If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: W3Schools is optimized for learning and training. May 17, 2020; How to Generate 7 Digit Unique Random String Using PHP?
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ func_math_mt_rand.asp
PHP mt_rand() Function
Example tip: If you want a random integer between 10 and 100 (inclusive), use mt_rand (10,100). ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com ยท If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com ยท HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ func_math_srand.asp
PHP srand() Function
Tip: From PHP 4.2.0, the random number generator is seeded automatically and there is no need to use this function. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
๐ŸŒ
W3Schools
www-db.deis.unibo.it โ€บ courses โ€บ TW โ€บ DOCS โ€บ w3schools โ€บ php โ€บ func_math_rand.asp.html
PHP rand() Function
Tip: The mt_rand() function produces a better random value, and is 4 times faster than rand(). ... Color Converter Google Maps Animated Buttons Modal Boxes Modal Images Tooltips Loaders JS Animations Progress Bars Dropdowns Slideshow Side Navigation HTML Includes Color Palettes Code Coloring ...
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ blog โ€บ software development โ€บ how to generate a random string in php: 8 ways with examples
8 Different Methods to Generate a Random String in PHP
February 13, 2025 - ... <?php $n = 12; // Set the length of the random substring function getRandomStringWithSha1($n) { // Generate a random hash by hashing some random data (e.g., current time and a random number) $randomHash = sha1(mt_rand() .
๐ŸŒ
DEV Community
dev.to โ€บ codeanddeploy โ€บ generate-random-string-in-php-j9e
Generate Random String in PHP - DEV Community
May 1, 2023 - Kindly visit here https://codeanddeploy.com/blog/php/generate-random-string-in-php if you want to download this code.
Top answer
1 of 16
318

Security warning: rand() is not a cryptographically secure pseudorandom number generator. Look elsewhere for generating a cryptographically secure pseudorandom string in PHP.

Try this (use strlen instead of count, because count on a string is always 1):

function randomPassword() {
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

Demo

2 of 16
162

TL;DR:

  • Use random_int() and the given random_str() below.
  • If you don't have random_int(), use random_compat.

Explanation:

Since you are generating a password, you need to ensure that the password you generate is unpredictable, and the only way to ensure this property is present in your implementation is to use a cryptographically secure pseudorandom number generator (CSPRNG).

The requirement for a CSPRNG can be relaxed for the general case of random strings, but not when security is involved.

The simple, secure, and correct answer to password generation in PHP is to use RandomLib and don't reinvent the wheel. This library has been audited by industry security experts, as well as myself.

For developers who prefer inventing your own solution, PHP 7.0.0 will provide random_int() for this purpose. If you're still on PHP 5.x, we wrote a PHP 5 polyfill for random_int() so you can use the new API before PHP 7 is released. Using our random_int() polyfill is probably safer than writing your own implementation.

With a secure random integer generator on hand, generating a secure random string is easier than pie:

<?php
/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    $length,
    $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
) {
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    if ($max < 1) {
        throw new Exception('$keyspace must be at least two characters long');
    }
    for ($i = 0; $i < $length; ++$i) {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
}
๐ŸŒ
Code And Deploy
codeanddeploy.com โ€บ home โ€บ blog โ€บ php โ€บ generate random string in php
Generate Random String in PHP - Code And Deploy
August 6, 2021 - <?php function randomString($length = 10) { // Set the chars $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Count the total chars $totalChars = strlen($chars); // Get the total repeat $totalRepeat = ceil($length...
๐ŸŒ
HTML Code Generator
html-code-generator.com โ€บ php โ€บ random-string-number
PHP Random String And Number Generation Functions
The following PHP function creates a random string using a mix of uppercase and lowercase letters: ... <?php function generateRandomString($length = 10) { $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } // usage echo generateRandomString(12); // Output: AbcDefGhIjKl
๐ŸŒ
Uptimia
uptimia.com โ€บ home โ€บ questions โ€บ how to generate a random string in php?
How To Generate a Random String in PHP?
October 10, 2024 - Learn how to create random strings in PHP with simple methods and code examples. Useful for generating unique IDs, passwords, and more.