Create a random string with PHP

php-banner

print
How to create a random string with PHP.

Step 1:

Include the following function somewhere.

function randomstring($length)
{
  $string = "";
  $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  for($i=0;$i<$length;$i++)
  $string.=substr($chars,rand(0,strlen($chars)),1);
  return $string;
}

I’ve only included upper and lower case characters here, but you can add anything to the $chars variable, and they will be included and picked at random.

Usage:

Just send the length of the string you want to return to the function when you call it, and it will return your random string.  So a random 15 character string would be:

$randomString= randomstring(15);

 

Share this post:
Related Posts
Ensure only a UK decimal value is added to a textbox – JavaScript
Getting the ID of draggable and droppable elements – jQuery
4 Comments
  • Berry
    Oct 22,2018 at 3:06 pm

    Thank you for the article

  • lc
    Sep 6,2018 at 7:49 am

    Cool thanks

  • Arthur
    Aug 20,2018 at 10:12 pm

    Thanks for the article

    • Fluffy
      Aug 24,2018 at 7:18 pm

      You’re welcome 🙂

Leave a Comment