- PHP

Make Random String in PHP

To make a random string in PHP:

  1. Precise the characters you want to use.
  2. Make a loop with your wanted string length as a number of iterations.
  3. Inside the loop, generate a random character and add it to the existing variable with the string.
  4. After all iterations, get your random string.

Example:

<?php

function randomString($length = 6) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';

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

    return $randomString;
}

echo randomString(10);

?>