Cake-PHP

Generate random strings using PHP

Sometimes you want to create random strings. The can be handy in different cases such as a random session_id, a temporary password when the user resets it and many more. This is a PHP function that accepts the length of the string as a parameter. The default value in case nothing is provided is 10:

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

Call it like this:

$randomString = generateRandomString(15);

Leave a Reply