How to generate a random alphanumeric string in PHP

Sometimes, we need to generate a random string with letters and numbers to meet a specific requirement in the project. Using PHP function str_shuffle() we can easily generate it. Define a string of all possible digits and letters; shuffle them and take a subtring of a specific length you want.

We will just create a php program to show you how you can generate a random alphanumeric string of certain length. This string can be used when ever you want some random string of numbers and letters.

generate Random String in PHP

This is a simple page with a button to generate the string. When user opens the page it will have a string generated and displayed. If user clicks on Generate Again button it will display a newly generated string.

Let me show you the code below for random_str.php

index.php

A variable $data is defined to store a string consisting of all possible characters to be used in the generated string. You can define your own set of characters here. I have used digits 0-9, lower case and upper case alphabets. You can also add some special characters, if you want to use it as password generator.

Then, two PHP functions are used on the string. First, str_shuffle() and then substr() on $data. Using str_shuffle($data), characters are shuffled, their orders are changed. Then, first 8 characters of the shuffled string is taken. This is stored in $str variable.

Generated string is then displayed. A button is used to regenerate the string.

Below is my custom stylesheet

style.css

php random stringTest the Application

Make sure your in your XAMPP control panel Apache and MySQL services are running. Open the browser and run localhost/random_str. You will see the page opened with string displayed in blue color.

php random password

If you click on "Generate Again" button you will see a new string is displayed .

php Random string generation with letters and numbersDownload Source Code

I have put all codes in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can directly use the code or you can modify them as per your requirements.

generate random 8 digit string in PHPConclusion

In this example, I have showed how you can write PHP code to generate a random staring. You can extend it to add some other characters in the string as per your requirement. Add some special characters and also make the starting position random instead of starting from zero position. You can then use it as password generator. Hope it will be useful for you.