Generate random string using php and javascript

Here you’ll see the custom php and javascript function to generate random string of selected length, We always need this feature for generataing random password or OTP type of things in our project, So this may help you to generate random string using php and javascript.

Using PHP

<?php
function GenRndString($length)
{
	$chars = '[email protected]!#$%^&*()';
    if($length > 0)
    {
    	$rndString = '';
	    for ($i = 0; $i < $length; $i++) {
	        $rndString .= $chars[rand(0, (strlen($chars) - 1))];
	    }
        return $rndString;
    }
}
?>

Copy and paste above function and call it where random string required.

<?= GenRndString(10); ?>

Where: 10 is the length of the string.


Using JVASCRIPT

<script>
function GenRndString(length)
{
 
    var chars = '[email protected]!#$%^&*()';
    if(length > 0)
    var rndString = '';
    for( var i=0; i < length; i++ )
        rndString += chars.charAt(Math.floor(Math.random() * chars.length));
 
    return rndString;
}
 
</script>

Call this function where random string required.

<script>
console.log(GenRndString(10));
alert(GenRndString(10));
</script>

DEMO

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.