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?
To answer this question specifically, two problems:
$randstring is not in scope when you echo it.
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[random_int(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 previous version of this answer used rand() instead of random_int() and therefore generated predictable random strings. So it was changed to be more secure, following advice from this answer.
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 to repeat.
One more way.
UPDATED (now this generates any length of string):
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}
echo generateRandomString(); // OR: generateRandomString(24)
That's it. :)
There are a lot of answers to this question, but none of them leverage a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).
The simple, secure, and correct answer is to use RandomLib and 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 PHP 5.x, we wrote a PHP 5 polyfill for random_int() so you can use the new API even before you upgrade to PHP 7.
Safely generating random integers in PHP isn't a trivial task. You should always check 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 PHP 5 as well.
*
* For PHP 7, random_int is a PHP core function
* For PHP 5.x, depends on https://github.com/paragonie/random_compat
*
* #param int $length How many characters do we want?
* #param string $keyspace A string of all possible characters
* to select from
* #return string
*/
function random_str(
int $length = 64,
string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
if ($length < 1) {
throw new \RangeException("Length must be a positive integer");
}
$pieces = [];
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pieces []= $keyspace[random_int(0, $max)];
}
return implode('', $pieces);
}
Usage:
$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
Demo: https://3v4l.org/IMJGF (Ignore the PHP 5 failures; it needs random_compat)
This creates a 20 character long hexadecimal string:
$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
In PHP 7 (random_bytes()):
$string = base64_encode(random_bytes(10)); // ~14 characters, includes /=+
// or
$string = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(32))), 0, 32); // 32 characters, without /=+
// or
$string = bin2hex(random_bytes(10)); // 20 characters, only 0-9a-f
#tasmaniski: your answer worked for me. I had the same problem, and I would suggest it for those who are ever looking for the same answer. Here it is from #tasmaniski:
<?php
$random = substr(md5(mt_rand()), 0, 7);
echo $random;
?>
Here is a youtube video showing us how to create a random number
Depending on your application (I wanted to generate passwords), you could use
$string = base64_encode(openssl_random_pseudo_bytes(30));
Being base64, they may contain = or - as well as the requested characters. You could generate a longer string, then filter and trim it to remove those.
openssl_random_pseudo_bytes seems to be the recommended way way to generate a proper random number in php. Why rand doesn't use /dev/random I don't know.
PHP 7+ Generate cryptographically secure random bytes using random_bytes function.
$bytes = random_bytes(16);
echo bin2hex($bytes);
Possible output
da821217e61e33ed4b2dd96f8439056c
PHP 5.3+ Generate pseudo-random bytes using openssl_random_pseudo_bytes function.
$bytes = openssl_random_pseudo_bytes(16);
echo bin2hex($bytes);
Possible output
e2d1254506fbb6cd842cd640333214ad
The best use case could be
function getRandomBytes($length = 16)
{
if (function_exists('random_bytes')) {
$bytes = random_bytes($length / 2);
} else {
$bytes = openssl_random_pseudo_bytes($length / 2);
}
return bin2hex($bytes);
}
echo getRandomBytes();
Possible output
ba8cc342bdf91143
Here is a simple one-liner that generates a true random string without any script level looping or use of OpenSSL libraries.
echo substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', mt_rand(1,10))), 1, 10);
To break it down so the parameters are clear
// Character List to Pick from
$chrList = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Minimum/Maximum times to repeat character List to seed from
$chrRepeatMin = 1; // Minimum times to repeat the seed string
$chrRepeatMax = 10; // Maximum times to repeat the seed string
// Length of Random String returned
$chrRandomLength = 10;
// The ONE LINE random command with the above variables.
echo substr(str_shuffle(str_repeat($chrList, mt_rand($chrRepeatMin,$chrRepeatMax))), 1, $chrRandomLength);
This method works by randomly repeating the character list, then shuffles the combined string, and returns the number of characters specified.
You can further randomize this, by randomizing the length of the returned string, replacing $chrRandomLength with mt_rand(8, 15) (for a random string between 8 and 15 characters).
A better way to implement this function is:
function RandomString($length) {
$keys = array_merge(range(0,9), range('a', 'z'));
$key = "";
for($i=0; $i < $length; $i++) {
$key .= $keys[mt_rand(0, count($keys) - 1)];
}
return $key;
}
echo RandomString(20);
mt_rand is more random according to this and this in PHP 7. The rand function is an alias of mt_rand.
function generateRandomString($length = 15)
{
return substr(sha1(rand()), 0, $length);
}
Tada!
$randstring in the function scope is not the same as the scope where you call it. You have to assign the return value to a variable.
$randstring = RandomString();
echo $randstring;
Or just directly echo the return value:
echo RandomString();
Also, in your function you have a little mistake. Within the for loop, you need to use .= so each character gets appended to the string. By using = you are overwriting it with each new character instead of appending.
$randstring .= $characters[rand(0, strlen($characters))];
First, you define the alphabet you want to use:
$alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$special = '~!##$%^&*(){}[],./?';
$alphabet = $alphanum . $special;
Then, use openssl_random_pseudo_bytes() to generate proper random data:
$len = 12; // length of password
$random = openssl_random_pseudo_bytes($len);
Finally, you use this random data to create the password. Because each character in $random can be chr(0) until chr(255), the code uses the remainder after division of its ordinal value with $alphabet_length to make sure only characters from the alphabet are picked (note that doing so biases the randomness):
$alphabet_length = strlen($alphabet);
$password = '';
for ($i = 0; $i < $len; ++$i) {
$password .= $alphabet[ord($random[$i]) % $alphabet_length];
}
Alternatively, and generally better, is to use RandomLib and SecurityLib:
use SecurityLib\Strength;
$factory = new RandomLib\Factory;
$generator = $factory->getGenerator(new Strength(Strength::MEDIUM));
$password = $generator->generateString(12, $alphabet);
I've tested performance of most popular functions there, the time which is needed to generate 1'000'000 strings of 32 symbols on my box is:
2.5 $s = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,32);
1.9 $s = base64_encode(openssl_random_pseudo_bytes(24));
1.68 $s = bin2hex(openssl_random_pseudo_bytes(16));
0.63 $s = base64_encode(random_bytes(24));
0.62 $s = bin2hex(random_bytes(16));
0.37 $s = substr(md5(rand()), 0, 32);
0.37 $s = substr(md5(mt_rand()), 0, 32);
Please note it is not important how long it really was but which is slower and which one is faster so you can select according to your requirements including cryptography-readiness etc.
substr() around MD5 was added for sake of accuracy if you need string which is shorter than 32 symbols.
For sake of answer: the string was not concatenated but overwritten and result of the function was not stored.
Here's my simple one line solution to generate a use friendly random password, excluding the characters that lookalike such as "1" and "l", "O" and "0", etc... here it is 5 characters but you can easily change it of course:
$user_password = substr(str_shuffle('abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789'),0,5);
One very quick way is to do something like:
substr(md5(rand()),0,10);
This will generate a random string with the length of 10 chars. Of course, some might say it's a bit more heavy on the computation side, but nowadays processors are optimized to run md5 or sha256 algorithm very quickly. And of course, if the rand() function returns the same value, the result will be the same, having a 1 / 32767 chance of being the same. If security's the issue, then just change rand() to mt_rand()
function gen_uid($l=5){
return substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 10, $l);
}
echo gen_uid();
Default Value[5]: WvPJz
echo gen_uid(30);
Value[30]: cAiGgtf1lDpFWoVwjykNKXxv6SC4Q2
Short Methods..
Here are some shortest method to generate the random string
<?php
echo $my_rand_strng = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), -15);
echo substr(md5(rand()), 0, 7);
echo str_shuffle(MD5(microtime()));
?>
Helper function from Laravel 5 framework
/**
* Generate a "random" alpha-numeric string.
*
* Should not be considered sufficient for cryptography, etc.
*
* #param int $length
* #return string
*/
function str_random($length = 16)
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}
Since php7, there is the random_bytes functions.
https://www.php.net/manual/ru/function.random-bytes.php
So you can generate a random string like that
<?php
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
?>
from the yii2 framework
/**
* Generates a random string of specified length.
* The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
*
* #param int $length the length of the key in characters
* #return string the generated random key
*/
function generateRandomString($length = 10) {
$bytes = random_bytes($length);
return substr(strtr(base64_encode($bytes), '+/', '-_'), 0, $length);
}
function rndStr($len = 64) {
$randomData = file_get_contents('/dev/urandom', false, null, 0, $len) . uniqid(mt_rand(), true);
$str = substr(str_replace(array('/','=','+'),'', base64_encode($randomData)),0,$len);
return $str;
}
This one was taken from adminer sources:
/** Get a random string
* #return string 32 hexadecimal characters
*/
function rand_string() {
return md5(uniqid(mt_rand(), true));
}
Adminer, database management tool written in PHP.
/**
* #param int $length
* #param string $abc
* #return string
*/
function generateRandomString($length = 10, $abc = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
{
return substr(str_shuffle($abc), 0, $length);
}
Source from http://www.xeweb.net/2011/02/11/generate-a-random-string-a-z-0-9-in-php/
Another one-liner, which generates a random string of 10 characters with letters and numbers. It will create an array with range (adjust the second parameter to set the size), loops over this array and assigns a random ASCII character (range 0-9 or a-z), then implodes the array to get a string.
$str = implode('', array_map(function () { return chr(rand(0, 1) ? rand(48, 57) : rand(97, 122)); }, range(0, 9)));
Note: this only works in PHP 5.3 and later
One liner.
It is fast for huge strings with some uniqueness.
function random_string($length){
return substr(str_repeat(md5(rand()), ceil($length/32)), 0, $length);
}
function randomString($length = 5) {
return substr(str_shuffle(implode(array_merge(range('A','Z'), range('a','z'), range(0,9)))), 0, $length);
}
Here is how I am doing it to get a true unique random key:
$Length = 10;
$RandomString = substr(str_shuffle(md5(time())), 0, $Length);
echo $RandomString;
You can use time() since it is a Unix timestamp and is always unique compared to other random mentioned above. You can then generate the md5sum of that and take the desired length you need from the generated MD5 string. In this case I am using 10 characters, and I could use a longer string if I would want to make it more unique.
I hope this helps.
The edited version of the function works fine, but there is just one issue I found: You used the wrong character to enclose $characters, so the ’ character is sometimes part of the random string that is generated.
To fix this, change:
$characters = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
to:
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
This way only the enclosed characters are used, and the ’ character will never be a part of the random string that is generated.
function generateRandomString($length = 10, $hasNumber = true, $hasLowercase = true, $hasUppercase = true): string
{
$string = '';
if ($hasNumber)
$string .= '0123456789';
if ($hasLowercase)
$string .= 'abcdefghijklmnopqrstuvwxyz';
if ($hasUppercase)
$string .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($x = $string, ceil($length / strlen($x)))), 1, $length);
}
and use:
echo generateRandomString(32);
I liked the last comment which used openssl_random_pseudo_bytes, but it wasn't a solution for me as I still had to remove the characters I didn't want, and I wasn't able to get a set length string. Here is my solution...
function rndStr($len = 20) {
$rnd='';
for($i=0;$i<$len;$i++) {
do {
$byte = openssl_random_pseudo_bytes(1);
$asc = chr(base_convert(substr(bin2hex($byte),0,2),16,10));
} while(!ctype_alnum($asc));
$rnd .= $asc;
}
return $rnd;
}
What is the best way to generate random captchas to avoid the malicious robots attached?
way 1:
function _generateRandom( $length = 4, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) {
return substr( str_shuffle( $chars ), 0, $length );
}
way 2:
function _generateRandom($length=4)
{
$_rand_src = array(
array(48,57) //digits
, array(97,122) //lowercase chars
);
srand ((double) microtime() * 1000000);
$random_string = "";
for($i=0;$i<$length;$i++){
$i1=rand(0,sizeof($_rand_src)-1);
$random_string .= chr(rand($_rand_src[$i1][0],$_rand_src[$i1][1]));
}
return $random_string;
}
Or way 3...
Or not mind the random process...
I still don't know how a robot can guess the generated random words so that they can still submit the post form?
Well if you attach a value for CAPTCHA inside the form, the robot can read it... :)
Robots can also read an image and in some cases interpret the image into letters using a very common technique called Optical character recognition (OCR) That's why many CAPTCHAs are obfuscated and warped, to try and confused the OCR algorithms
If you want to generate random characters, here's a function of mine
# Generate random characters
# #param $l = length
# #param $s = use symbols?
# #param $a = use alphabetical?
# #param $n = use numbers?
function rand_chars($l=8,$s=1,$a=1,$n=1) {
$string = ''; $chars = array();
if ($s) $chars = array_merge($chars,array(
33,35,36,37,38,40,41,42,43,44,45,
46,47,58,59,60,61,62,63,64,91,93,
94,95,123,124,125,126
));
if ($a) $chars = array_merge($chars,array(
65,66,67,68,69,70,71,72,73,74,
75,76,77,78,79,80,81,82,83,84,
85,86,87,88,89,90,
97,98,99,100,101,102,103,104,105,106,
107,108,109,110,111,112,113,114,115,116,
117,118,119,120,121,122
));
if ($n) $chars = array_merge($chars,array(
48,49,50,51,52,53,54,55,56,57
));
for ($i=0;$i<$l;$i++) {shuffle($chars);$string.=chr(reset($chars));}
return $string;
}
Robots won't guess your algorithm, but will try to read what is visible. I assume you don't echo your string, if you do, that's like having no captcha at all. Another fault that is often made, is that people load images for the generated string and name (or alt) the image the exact same as the distorted character that represents it. That wouldn't do well either.
hi i am using codeigniter . i want to validate my credit card details . i saw there are classes in php to validate credit card numbers . i saw a helper in codeigniter to validate credit cards
http://codeigniter.com/wiki/Credit_Card_Helper
/**
* Truncates a card number retaining only the first 4 and the last 4 digits. It then returns the truncated form.
*
* #param string The card number to truncate.
* #return string The truncated card number.
*/
function truncate_card($card_num) {
$padsize = (strlen($card_num) < 7 ? 0 : strlen($card_num) - 7);
return substr($card_num, 0, 4) . str_repeat('X', $padsize). substr($card_num, -3);
}
/**
* Validates a card expiry date. Finds the midnight on first day of the following
* month and ensures that is greater than the current time (cards expire at the
* end of the printed month). Assumes basic sanity checks have already been performed
* on month/year (i.e. length, numeric, etc).
*
* #param integer The expiry month shown on the card.
* #param integer The expiry year printed on the card.
* #return boolean Returns true if the card is still valid, false if it has expired.
*/
function card_expiry_valid($month, $year) {
$expiry_date = mktime(0, 0, 0, ($month + 1), 1, $year);
return ($expiry_date > time());
}
/**
* Strips all non-numerics from the card number.
*
* #param string The card number to clean up.
* #return string The stripped down card number.
*/
function card_number_clean($number) {
return ereg_replace("[^0-9]", "", $number);
}
/**
* Uses the Luhn algorithm (aka Mod10) <http://en.wikipedia.org/wiki/Luhn_algorithm>
* to perform basic validation of a credit card number.
*
* #param string The card number to validate.
* #return boolean True if valid according to the Luhn algorith, false otherwise.
*/
function card_number_valid ($card_number) {
$card_number = strrev(card_number_clean($card_number));
$sum = 0;
for ($i = 0; $i < strlen($card_number); $i++) {
$digit = substr($card_number, $i, 1);
// Double every second digit
if ($i % 2 == 1) {
$digit *= 2;
}
// Add digits of 2-digit numbers together
if ($digit > 9) {
$digit = ($digit % 10) + floor($digit / 10);
}
$sum += $digit;
}
// If the total has no remainder it's OK
return ($sum % 10 == 0);
}
?>
it uses a common validation . but i want a validation according to card type like this
http://www.braemoor.co.uk/software/creditcard.php
is there any libraries or helpers in codeigniter . please help.....................
As people already told you, CodeIgniter is a php framework, coded using php, works in a php environment and makes use of..,php classes and functions :).
What's more, the file you linked to is a simple function. One function. You know what you can do? Take the file as it is, name it creditcard_helper.php, put it inside the helpers folder, open it and place the whole code inside this snippet (ugly but necessary, as whenever you'll load the helper a second time it would give you error otherwise):
if(!function_exists('checkCreditCard')
{
//the whole content goes here untouched;
}
And you're set. Just use:
$this->load->helper('creditcard');
if(checkCreditCard($cardnumber, $cardname, &$errornumber, &$errortext))
{
echo 'card OK';
}
else
{
echo 'wrong card type/number';
}
I found this helper inside the CodeIgniter Github wiki page. When dropped inside your helpers folder, you can then use the functions from the file in a controller or model you load it in.