Table of contents

Generate Random String in PHP

In this post, I will show you an example function to generate a random string in PHP. This function is usually used to generate alphanumeric strings when creating a file name, coupon code, auto password generator, and more.

 

In this function is using PHP built-in functions such as strlen(), ceil(), str_repeat(), str_shuffle(), and substr().

 

strlen() - help to count the total chars available

ceil() - help to round up the result of length to generate random string / total chars available

str_repeat() - helps to repeat the result string

str_shuffle() - helps to randomly shuffles all available string

substr() - helps to get the random string generated

 

Now I will show you the complete function of this random string generator.

<?php

function randomString($length = 10) {
	// Set the chars
	$chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

	// Count the total chars
	$totalChars = strlen($chars);

	// Get the total repeat
	$totalRepeat = ceil($length/$totalChars);

	// Repeat the string
	$repeatString = str_repeat($chars, $totalRepeat);

	// Shuffle the string result
	$shuffleString = str_shuffle($repeatString);

	// get the result random string
    return substr($shuffleString,1,$length);
}

?>

 

Now, you have the function already to generate random string its time to call this function and display the result.

<?php

function randomString($length = 10) {
	// Set the chars
	$chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

	// Count the total chars
	$totalChars = strlen($chars);

	// Get the total repeat
	$totalRepeat = ceil($length/$totalChars);

	// Repeat the string
	$repeatString = str_repeat($chars, $totalRepeat);

	// Shuffle the string result
	$shuffleString = str_shuffle($repeatString);

	// get the result random string
    return substr($shuffleString,1,$length);
}

// Display the generated string
echo randomString();

?>

 

As you can see above code I echo the randomString() and this is the result below:

3tvplJFMSO

 

Now you have already how to generate random strings in PHP. It's time to implement it in your project. I hope this example may help you. Don't forget to share this post if you think this is helpful to you :)

 

Cheers :)