PHP : Random string with numbers and letters

Mon, Oct 1, 2007

PHP

I thought that some of you might find it useful to learn how to generate a string with random numbers and letters. I wrote a quick function for generating a string like this. See it below :

function genRandomString() {
    $length = 10;
    $characters = ‘0123456789abcdefghijklmnopqrstuvwxyz’;
    $string = ;    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}

, , , , ,

This post was written by:

Antonie Potgieter - who has written 46 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

7 Comments For This Post

  1. Jake Holman Says:

    Nice, came across this with a quick google search.

    You have some syntax incorrect though. As it is now it will return something like 1f’q4w’432″2 - You don’t want those odd characters in there right?

    Remove $string = “; it will get defined anyway. Also replace the ‘ around the $characters declaration and replace it with ” - it should look like this:

    $characters = “0123456789abcdefghijklmnopqrstuvwxyz”;

    That will mean the return will only have letters and numbers ;)

  2. lost-in-code Says:

    Hi Jake,

    Thank you for the comment.

    It is the encoding of Wordpress which causes those entities.
    In reality, you have to replace them with proper html characters when you use the code. Here is a sample :

    http://lost-in-code.com/wp-content/_randomstring.php

    It works well.

    All the best,
    Antonie

  3. Jake Holman Says:

    Oh then I do apolosgize! Didn’t consider WP might be screwing things up.

    But thank you for the snippet there. I used it in http://www.jakeisonline.com/s/ - something I was working on for work.

    Thanks!

  4. Eric Says:

    Also found this via google. Nice function, just wanted to drop a line and say thanks, I used this for my blog.

  5. Ryan Says:

    Thanks for the clip, nice and clean!

    -Ryan

  6. Brad Hanson Says:

    Shouldn’t it be strlen()-1 instead of strlen()?

    mt_rand() will sometimes return int $max and there isn’t a proper value in $characters[strlen()]

  7. Erwin Says:

    Great, thanks.

Leave a Reply