Saturday, July 6, 2013

PHP Code Snippets: Generate a random string

Generating random strings might be very useful when developing a website. You can use random strings for various purposes:
2) Generating Coupon codes for a shopping website
And lots more! 
Soon, I will add tutorials to create all the examples that I have mentioned above. But for now, just take a look at the function I have given below:

The variable $length can be set to the length of string that you want to have.

How to use the function?

Just call it whenever you want the random string to interact with the PHP script you are designing.
Ex: $myrand = generatestring(8) // Generates 8 character random string


Add more type of characters you wanna include in your PHP script to the variable in the function $charset

More coding at Let's Code.


  1. I have an alternative for you:

    function generatestring( $length ) {
    $charset = 'abcdefg...'; // same as yours
    return( substr( str_shuffle( $charset ), 0, $length) );

  2. Great Way, I also wrote a post about it, Have a Look for more methods !!
    Generate Random String in PHP