Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP random string generator

Tags:

string

php

random

I'm trying to create a randomized string in PHP, and I get absolutely no output with this:

<?php     function RandomString()     {         $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';         $randstring = '';         for ($i = 0; $i < 10; $i++) {             $randstring = $characters[rand(0, strlen($characters))];         }         return $randstring;     }      RandomString();     echo $randstring; 

What am I doing wrong?

like image 901
Captain Lightning Avatar asked Dec 04 '10 22:12

Captain Lightning


People also ask

How can I generate 5 random numbers in PHP?

The rand() is an inbuilt function in PHP used to generate a random number ie., it can generate a random integer value in the range [min, max]. Syntax: rand(); The rand() function is used to generate a random integer.

What is Mt_rand function in PHP?

The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

How do you generate a non repeating random number in PHP?

php $check = array(); function generateNumber() { global $check; $page_no = mt_rand(1,20); $check[] = $page_no; if (count($check) != 1) { foreach ($check as $val) { if ($val == $page_no) { $page_no = mt_rand(1,10); continue; } } return $page_no; } else { return $page_no; } } ?>


1 Answers

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.

like image 81
Stephen Watkins Avatar answered Sep 21 '22 21:09

Stephen Watkins