Generate Random String using PHP

In this post, we will be writing a simple PHP function that will generate random string of desired length. We can generate a random string with fixed set of characters using simple string functions like substr, str_shuffle and str_repeat.

<h1>Generate Random String using PHP</h1> 

<?php
  function generateRandomString($length=10){ 
    	return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',ceil($length/strlen($x)))),1,$length);
    }
?>

<p>Random String of 10 characters: <strong><?php echo generateRandomString();?></strong></p>
<p>Random String of 20 characters:<strong><?php echo generateRandomString(20);?></strong></p>
<p>Random String of 4 characters: <strong><?php echo generateRandomString(4);?></strong></p>
<p>Random String of 1 character:<strong><?php echo generateRandomString(1);?></strong></p>

Follow this video for complete guidance :



Recommended For You

About the Author: Admin