December 27, 2023 5:02 am

How to generate random string in PHP

Are you looking for random, number, lower case upper case or alpha numeric etc using PHP. Just look at this post i have implemented it in a simple script.

[wpdm_file id=11]

Simple PHP Function

  function randomString($length, $type = '') {
  // Select which type of characters you want in your random string
  switch($type) {
    case 'num':
      // Use only numbers
      $salt = '1234567890';
    case 'lower':
      // Use only lowercase letters
      $salt = 'abcdefghijklmnopqrstuvwxyz';
    case 'upper':
      // Use only uppercase letters
      // Use uppercase, lowercase, numbers, and symbols
      $salt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  $rand = '';
  $i = 0;
  while ($i < $length) { // Loop until you have met the length
    $num = rand() % strlen($salt);
    $tmp = substr($salt, $num, 1);
    $rand = $rand . $tmp;
  return $rand; // Return the random string

 Call Function

echo randomString(10, $type = ''); // It will show 10 digit alpha numeric string.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.

Tutorial Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *