How to Create a Random String Using PHP

PHP random string generator

To answer this question specifically, two problems:

  1. $randstring is not in scope when you echo it.
  2. The characters are not getting concatenated together in the loop.

Here's a code snippet with the corrections:

function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}

Output the random string with the call below:

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();

Please note that this generates predictable random strings. If you want to create secure tokens, see this answer.

How to create a random string using PHP?

Well, you didn't clarify all the questions I asked in my comment, but I'll assume that you want a function that can take a string of "possible" characters and a length of string to return. Commented thoroughly as requested, using more variables than I would normally, for clarity:

function get_random_string($valid_chars, $length)
{
// start with an empty random string
$random_string = "";

// count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);

// repeat the steps until we've created a string of the right length
for ($i = 0; $i < $length; $i++)
{
// pick a random number from 1 up to the number of valid chars
$random_pick = mt_rand(1, $num_valid_chars);

// take the random character out of the string of valid chars
// subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];

// add the randomly-chosen char onto the end of our string so far
$random_string .= $random_char;
}

// return our finished random string
return $random_string;
}

To call this function with your example data, you'd call it something like:

$original_string = 'abcdefghi';
$random_string = get_random_string($original_string, 6);

Note that this function doesn't check for uniqueness in the valid chars passed to it. For example, if you called it with a valid chars string of 'AAAB', it would be three times more likely to choose an A for each letter as a B. That could be considered a bug or a feature, depending on your needs.

php Random string generation with letters and numbers

Use the below code.

For digits and characters

$length = 10;    
echo substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'),1,$length);

For only characters

$length = 10;    
echo substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'),1,$length);

For only digits

$length = 10;    
echo substr(str_shuffle('0123456789'),1,$length);

PHP random string generator

To answer this question specifically, two problems:

  1. $randstring is not in scope when you echo it.
  2. The characters are not getting concatenated together in the loop.

Here's a code snippet with the corrections:

function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}

Output the random string with the call below:

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();

Please note that this generates predictable random strings. If you want to create secure tokens, see this answer.

One-line PHP random string generator?

Rather than shuffling the alphabet string , it is quicker to get a single random char .

Get a single random char from the string and then append the md5( time( ) ) to it . Before appending md5( time( ) ) remove one char from it so as to keep the resulting string length to 32 chars :

substr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", mt_rand(0, 51), 1).substr(md5(time()), 1);

Lowercase version :

substr("abcdefghijklmnopqrstuvwxyz", mt_rand(0, 25), 1).substr(md5(time()), 1);

Or even shorter and a tiny bit faster lowercase version :

chr(mt_rand(97, 122)).substr(md5(time()), 1);

/* or */

chr(mt_rand(ord('a'), ord('z'))).substr(md5(time()), 1);


A note to anyone trying to generate many random strings within a second:
Since
time( ) returns time in seconds , md5( time( ) ) will be same throughout a given second-of-time due to which if many random strings were generated within a second-of-time, those probably could end up having some duplicates .


I have tested using below code . This tests lower case version :

    $num_of_tests = 100000;

$correct = $incorrect = 0;

for( $i = 0; $i < $num_of_tests; $i++ )
{
$rand_str = substr( "abcdefghijklmnopqrstuvwxyz" ,mt_rand( 0 ,25 ) ,1 ) .substr( md5( time( ) ) ,1 );

$first_char_of_rand_str = substr( $rand_str ,0 ,1 );

if( ord( $first_char_of_rand_str ) < ord( 'a' ) or ord( $first_char_of_rand_str ) > ord( 'z' ) )
{
$incorrect++;
echo $rand_str ,'<br>';
}
else
{
$correct++;
}
}

echo 'Correct: ' ,$correct ,' . Incorrect: ' ,$incorrect ,' . Total: ' ,( $correct + $incorrect );

Random string generator PHP

You could try using $random = substr(str_shuffle(MD5(microtime())), 0, 8);, which will output the same amount of random characters as you have in your example. I actually prefer this method over most as it doesn't require you to put in the expected characters and even more importantly, it can be done in one line of code!

Generate random string in php/mysql

You can try the code below:

    function generate_random_string($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}

echo generate_random_string(15); // define amount of string length in parametre

Source: PHP random string generator

If you use random number as Random String code is below:

$number = range(100000,999999);
shuffle($number);
$ran_string = $number[0];
echo $ran_string;

How to generate a random, unique, alphanumeric string?

Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.

If you do not need it to be absolutely unique over time:

md5(uniqid(rand(), true))

Otherwise (given you have already determined a unique login for your user):

md5(uniqid($your_user_login, true))

How can I generate a random string using php and only once per day?

You can achieve the same result using a hash function with the current date.

$sehiradi.substr(sha1('someString'.date('Ymd')),0,5);

This will work for you, as the hash will always bring the same result with the same input. Everyday, the function will use a different input value, as the day changes.

EDIT: Using your values you can have:

$sehiradi = "diyarbakir";
$subdomainadi = $sehiradi.substr(sha1('someString'.date('Ymd')),0,5);

Please replace 'someString' with some key that you have in mind. The point is to make it hard for someone to know the source of your "random" string.



Related Topics



Leave a reply



Submit