0

How do I generate random 12 character char for URL of a page for the record in the database like how youtube does it with 11 characters https://www.youtube.com/watch?v=kDjirnJcanw

I want it to be unique for each entry in the database and consist of letters of upper and lower case, numbers and maybe (if not bad for security) even special characters.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Baris Sarac
  • 115
  • 1
  • 7

2 Answers2

2

Function:

function generateRandomString($length = 12) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

Then call it:

$randomString = generateRandomString();

Slightly adapted from Stephen Watkins' solution here

Community
  • 1
  • 1
Ben
  • 8,894
  • 7
  • 44
  • 80
1

This is a pretty naive approach, but you could define an array of allowed characters, and just randomly select N:

function randomString($length) {
   $string = '';
   $characters = "123456789abcdefghijklmnopqrstuvwxyzABCDEFHJKLMNPRTVWXYZ";
   $randMax = strlen($characters)-1;

   for ($i = 0; $i < $length; ++$i) {
       $string .= $characters[mt_rand(0, randMax)];
   }

   return $string;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350