Generate random string

<?php

/**

 * 

 * @param $size is an integer value ( length ) of string to be generated

 * @return string if a positive integer value is passed 

 * or NULL if a negative or non-integer number is given

 */

function get_random_string($size) {

    $size = intval($size);

    if ($size == 0) {

        // if an integer value is not given return NULL 

        return NULL;

    }

   

    // you can add more characters to this variable

    $charSet = "ABCHEFGHJKMNPQRSTUVWXYZ0123456789abchefghjkmnpqrstuvwxyz!@#%^&*()";

    $len = strlen($charSet);

    $str = '';

    $i = 0;

    while (strlen($str) < $size) {

        $num = rand(0, ($len-1));

        $tmp = substr($charSet, $num, 1);

        $str = $str . $tmp;

        $i++;

    }

    return $str;

}

 

// how to use this function

echo get_random_string(10);  // return hHA%y!bc)f (can be different)

echo get_random_string(5);  // return ajHm) (can be different)

?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s