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.

One Reply to “Generate random string using php and javascript”

  1. Hello Rohit,

    This tutorial is best for generating captcha.. Can you please tell me that how can display data on webpage by searching that data from MySql database.And if searching is by place and two or more field(row from table) have same location then display the two or more data(row) dynamically..

    Thanks in advance…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.