I"m trying to lớn create a randomized string in PHP., and I get absolutely no output with this:What am I doing wrong?
My one line solution for generate short string is substr(md5(rand()), 0, 7); good luchồng ... – tasmaniski Jun 21 "12 at 14:46
tasmaniski.. Your solution is ok.. But its less randomized! In your example the number of random strings that can be generated is limited by the kích thước of integer. ( 2^32 ) at the max.. In case of the other solution, you can generate ( 62^8 ).. In case, I want larger strings, then number of distinct strings remain at max 2^32, but in the other solution it increases khổng lồ ( 62^n ).. – Manu Dec 23 "13 at 8:12
You forgot to lớn add each new generated character lớn the string. You're just overwriting it as it is. Should be $randstring .= $characters.. – Spoông chồng Aquảng cáo 25 "14 at 9:28
CaptainLightning Can you please swap out the accepted answer for one of the more secure ones? :) – Scott Arciszewski Dec 8 "15 at 6:29
strlen($characters) => strlen($characters) - 1 - string length starts with 1 – Zippp Aquảng cáo 24 "17 at 13:07
To answer this question specifically, two problems:$randstring is not in scope when you emang lại it. The characters are not getting concatenated together in the loop.
Here"s a code snippet with the corrections:function generateRandomString($length = 10) return $randomString; }
đầu ra the random string with the Điện thoại tư vấn below:// Emang đến the random string. // Optionally, you can give sầu it a desired string length. echo generateRandomString();
Please note that this generates predictable random strings. If you want lớn create secure tokens, see this answer. Bạn đang xem: Function random php
Bạn đang xem: Function random php
edited Feb 5 "19 at 10:48
9,820 2 2 gold badges trăng tròn đôi mươi silver badges 33 33 bronze badges
answered Dec 4 "10 at 22:57
Stephen WatkinsStephen Watkins
22.8k 11 11 gold badges 59 59 silver badges 96 96 bronze badges
FranciscoPresencia, It's better "wasting" an extra variable as of calling an method in the compare condition of an loop. – Riteo Sonntag Aug 16 "13 at 8:58
All that work, why not just something lượt thích substr(str_shuffle(MD5(microtime())), 0, 10);? – SpYk3HH Atruyền thông quảng cáo 9 "14 at 13:06
Thanks for the code, but please change rand() lớn mt_rand(). I used your method and experienced a ton of collisions with names. – Nate Jul 25 "14 at 0:34
FranciscoPresencia vì chưng you have sầu any idea how horrifically inefficient that is? You are checking the length of a string twice per iteration! The strlen inside the loop should be cached in a variable before entering the loop as well. – developerbmw Nov 29 "14 at 6:51
This is not a good solution. The strings this generates will be predictable. :( – Scott Arciszewski Jun 29 "15 at 3:45
| Show 11 more comments
Note: str_shuffle() internally uses rand(), which is unsuitable for cryptography purposes (e.g. generating random passwords). You want a secure random number generator instead. It also doesn"t allow characters khổng lồ repeat.One more way.
UPDATED (now this generates any length of string):function generateRandomString($length = 10) emang lại generateRandomString(); // OR: generateRandomString(24)
That"s it. :)
edited May 23 "17 at 12:10
1 1 1 silver badge
answered Nov 3 "12 at 20:04
A. CheshirovA. Cheshirov
4,298 1 1 gold badge 11 11 silver badges 13 13 bronze badges
+1 for the shordemo answer :). But not the best answer for every use-case. This code will output strings where each character won't appear more than once (thus making it weaker for brute force attacks) và won't output anything longer than 62 characters. – David Dec 5 "12 at 9:55
Do not vì this, it is extremely weak. The longer you make your random string, the weaker it will be. – Abhi Beckert Feb 13 "13 at 21:38
Weak it may be, but it's quiông chồng and easy. Depending on the use-case, this is fine -- I've used it because I didn't need security or strength; just a quick-fire shuffle. I'm writing a unit chạy thử, và this gives me a suitably random input đầu vào lớn test with. – SDC Mar 12 "13 at 13:44
FranciscoPresencia the reason it is not secure is because it never uses the same character twice. That makes it a terrible password generator. Please everyone stop up voting this, it is totally insecure must never be used. As the password gets longer, the number of characters you must kiểm tra in a brute force gets shorter because you vì not bother testing any previously used character. – Abhi Beckert Aug 9 "13 at 19:33
FranciscoPresencia: I support your comments about avoiding using this for random passwords. However, I disagree that this answer should not be plus-one'd. I have plus-one'd this option for since it is an effective one-line solution for generating random strings (the original topic of this question). – bwright Dec 6 "13 at 17:11
| Show 14 more comments
There are a lot of answers lớn this question, but none of them leverage a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).
The simple, secure, and correct answer is lớn use RandomLib và don"t reinvent the wheel.
For those of you who insist on inventing your own solution, PHP. 7.0.0 will provide random_int() for this purpose; if you"re still on PHPhường 5.x, we wrote a PHPhường 5 polyfill for random_int() so you can use the new API even before you tăng cấp to lớn PHPhường 7.
Safely generating random integers in PHPhường isn"t a trivial task. You should always kiểm tra with your resident StackExchange cryptography experts before you deploy a home-grown algorithm in production.
With a secure integer generator in place, generating a random string with a CSPRNG is a walk in the park.
Creating a Secure, Random String/** * Generate a random string, using a cryptographically secure * pseudorandom number generator (random_int) * * This function uses type hints now (PHP 7+ only), but it was originally * written for PHPhường 5 as well. * * For PHPhường. 7, random_int is a PHPhường. core function * For PHP 5.x, depends on https://github.com/paragonie/random_compat * *
param int $length How many characters vày we want? *
param string $keyspace A string of all possible characters * khổng lồ select from *
return string */ function random_str( int $length = 64, string $keyspace = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ): string $pieces = <>; $max = mb_strlen($keyspace, "8bit") - 1; for ($i = 0; $i < $length; ++$i) return implode("", $pieces); }
Usage:$a = random_str(32); $b = random_str(8, "abcdefghijklmnopqrstuvwxyz"); $c = random_str();
Demo: https://3v4l.org/IMJGF (Ignore the PHPhường. 5 failures; it needs random_compat)