Generate Random Passwords in PHP

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

Here is a function I wrote to generate a random string in PHP. It is probably most useful for generating passwords. You can specify the length of the resulting string, as well as what characters are allowed. The default length is eight and the default character set is alphanumeric.

<?php

function random_string($length = 8, $chars = null) {
    if( empty($chars) ) $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    while( strlen($s) < $length) {
        $s .= substr($chars, rand(0, strlen($chars) - 1), 1);
    }
    return $s;
}

// Example
echo random_string(10);

?>
If you enjoyed this article, please share it with a friend!

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>