How to generate random password with PHP? - php

Or is there a software to auto generate random passwords?

Just build a string of random a-z, A-Z, 0-9 (or whatever you want) up to the desired length. Here's an example in PHP:
function generatePassword($length = 8) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$count = mb_strlen($chars);
for ($i = 0, $result = ''; $i < $length; $i++) {
$index = rand(0, $count - 1);
$result .= mb_substr($chars, $index, 1);
}
return $result;
}
To optimize, you can define $chars as a static variable or constant in the method (or parent class) if you'll be calling this function many times during a single execution.

Here's a simple solution. It will contain lowercase letters and numbers.
substr(str_shuffle(strtolower(sha1(rand() . time() . "my salt string"))),0, $PASSWORD_LENGTH);
Here's A stronger solution randomly generates the character codes in the desired character range for a random length within a desired range.
function generateRandomPassword() {
//Initialize the random password
$password = '';
//Initialize a random desired length
$desired_length = rand(8, 12);
for($length = 0; $length < $desired_length; $length++) {
//Append a random ASCII character (including symbols)
$password .= chr(rand(32, 126));
}
return $password;
}

I want to play the game. The simplest way would be to do:
function rand_passwd( $length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) {
return substr( str_shuffle( $chars ), 0, $length );
}
This is pretty much just a modification of the first answer. Specify the characters you want in the second parameters and the length of the password in the first.

This is how I do it.
$pw = "";
for ($i = 0; $i < 13; $i++)
{
$pw .= chr(rand(33, 126));
}

here is a function that generates a password with a minimum length, a minimum number of digits and a minimal number of letters.
function generatePassword() {
$min_length=8; //Minimum length of the password
$min_numbers=2; //Minimum of numbers AND special characters
$min_letters=2; //Minimum of letters
$password = '';
$numbers=0;
$letters=0;
$length=0;
while ( $length <= $min_length OR $numbers <= $min_numbers OR $letters <= $min_letters) {
$length+=1;
$type=rand(1, 3);
if ($type==1) {
$password .= chr(rand(33, 64)); //Numbers and special characters
$numbers+=1;
}elseif ($type==2) {
$password .= chr(rand(65, 90)); //A->Z
$letters+=1;
}else {
$password .= chr(rand(97, 122)); //a->z
$letters+=1;
}
}
return $password;
}

Another, very simple (and secure!) way to do this is the following (I generate all my own passwords that way):
base64_encode(random_bytes(12));
This generates a 16 character password that uses quite a sane range of characters.
However, depending on your requirements (for example if a user needs to type in their password), it may be desirable to remove characters that migth be confused (such as l, I, 1, 0, O, 5, S, and so on). In that case, the above solution is probably a bit too simple.

A good password should be a mixture of both uppercase, lowercase, has number, letters, has special characters and its more than 6 characters long. Here is function I use on my apps.
function randomPassword( $length = 8 )
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%^&*()_-=+;:,.?";
$length = rand(10, 16);
$password = substr( str_shuffle(sha1(rand() . time()) . $chars ), 0, $length );
return $password;
}

Also you can try a function that I wrote and is available form my blog. Advantage of this function is that it gives equal importance to lowercase, uppercase, numbers and special characters. It can be found here
PHP random password generator function

I like to shuffle array of random chars
$a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789");
shuffle($a);
echo implode($a); //maxlength
echo "\n".substr( implode($a), 0, 10 ); //instead of 10 => any length
//As function:
function getMeRandomPwd($length){
$a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789");
shuffle($a);
return substr( implode($a), 0, $length );
}
echo "\n".getMeRandomPwd(8)."\n".getMeRandomPwd(11);
// Outpus something like:
// 3Ai4Xf6R2I8bYGUmKgB9jpqo7ncV5teuQhkOHJCNrTP0sLFd1wxSMlEWvyaD
// 3Ai4Xf6R2I
// JsBKWFDa
// gfxsjr3dX70
If you need the password to be longer, just concatenate charlist a few times :)

function generate_password($length = 6) {
$password = '';
$chars = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
for ($i = 0; $i < $length; $i ++) {
$password .= $chars[array_rand($chars)];
}
return $password;
}

This function will include half digits and half numbers:
function generateMixedPassword($length = 8) {
$base = 'abcdefghijklmnopqrstuvwxyz';
$baseD = '0123456789';
$r = array();
for ($i = 0; $i < $length; $i += 2) {
$r[] = substr($base, rand(0, strlen($base) - 1), 1);
}
for ($i = 0; $i < $length; $i += 2) {
$r[] = substr($baseD, rand(0, strlen($baseD) - 1), 1);
}
shuffle($r);
return implode('', $r);
}
Using the same login, it can be extended to also include special characters

You could just use PEAR's Text_Password package - it supports quite a few algorithms for generating them; and frees up your time to go onto something else.

Pwgen-php produces save, pronounceable (easier to remember) passwords:
http://code.google.com/p/pwgen-php/
Might that be acceptable?

This function will generate more stronger password than most woted solution:
function generatePassword($size=8){
$p = openssl_random_pseudo_bytes(ceil($size*0.67), $crypto_strong);
$p = str_replace('=', '', base64_encode($p));
$p = strtr($p, '+/', '^*');
return substr($p, 0, $size);
}
Each character of password will be [A-Z] or [a-z] or ^ or *

use hackzilla/password-generator
it has many options to create different kind of passwords:
ComputerPasswordGenerator()
HybridPasswordGenerator() -> sjgX-PFjH-zxMz-PRDz-G6mx-wMJ4-ST24
HumanPasswordGenerator() -> Verkuemmerungen-verlottertet-dreinzuschauen (word list based. in this case a german word list)
RequirementPasswordGenerator()
ComputerPasswordGenerator
$generator
->setOptionValue(ComputerPasswordGenerator::OPTION_UPPER_CASE, true)
->setOptionValue(ComputerPasswordGenerator::OPTION_LOWER_CASE, true)
->setOptionValue(ComputerPasswordGenerator::OPTION_NUMBERS, true)
->setOptionValue(ComputerPasswordGenerator::OPTION_SYMBOLS, false)
;
$password = $generator->generatePassword();
RequirementPasswordGenerator
$generator
->setLength(16)
->setOptionValue(RequirementPasswordGenerator::OPTION_UPPER_CASE, true)
->setOptionValue(RequirementPasswordGenerator::OPTION_LOWER_CASE, true)
->setOptionValue(RequirementPasswordGenerator::OPTION_NUMBERS, true)
->setOptionValue(RequirementPasswordGenerator::OPTION_SYMBOLS, true)
->setMinimumCount(RequirementPasswordGenerator::OPTION_UPPER_CASE, 2)
->setMinimumCount(RequirementPasswordGenerator::OPTION_LOWER_CASE, 2)
->setMinimumCount(RequirementPasswordGenerator::OPTION_NUMBERS, 2)
->setMinimumCount(RequirementPasswordGenerator::OPTION_SYMBOLS, 2)
->setMaximumCount(RequirementPasswordGenerator::OPTION_UPPER_CASE, 8)
->setMaximumCount(RequirementPasswordGenerator::OPTION_LOWER_CASE, 8)
->setMaximumCount(RequirementPasswordGenerator::OPTION_NUMBERS, 8)
->setMaximumCount(RequirementPasswordGenerator::OPTION_SYMBOLS, 8)
;
$password = $generator->generatePassword();

I use st_split and implode function:
function genarateKey(){
$limit= 8;
$chars= 'abcdefghijklmnopqrstuvxwyz1234567890!##$%^&*()_+=-[]{}\|ABCDEFGHIJKLMNOPQRSTUVXWYZ';
$chararray= str_split($chars);
$gen=array();
for($i=0;$i<$limit;$i++){
$index=rand(0,strlen($chars)-1);
$gen[$i]= $chararray[$index];
}
return implode($gen); //converts array to string
}

Memorable password generator
function password($length)
{
$vowel = array(
'a',
'e',
'i',
'o',
'u',
);
$consonant = array(
'b',
'c',
'd',
'f',
'g',
'h',
'j',
'k',
'l',
'm',
'n',
'p',
'q',
'r',
's',
't',
'v',
'w',
'x',
'y',
'z',
);
$result = '';
for ($i = 0; $i < $length; $i++) {
if ($i % 2 == 0) {
$result .= $consonant[rand(0, 15)];
} else {
$result .= $vowel[rand(0, 4)];
}
}
return $result;
}
The result:
password(8);//kutekaku
password(11);//rahubabatul

I think better way to generate random password is below function, if someone want then you can use these for strong password
public function randPassword($upper = 2, $lower = 3, $numeric = 2, $other = 1) {
$pass_order = Array();
$passWord = '';
//Create contents of the password
for ($i = 0; $i < $upper; $i++) {
$pass_order[] = chr(rand(65, 90));
}
for ($i = 0; $i < $lower; $i++) {
$pass_order[] = chr(rand(97, 122));
}
for ($i = 0; $i < $numeric; $i++) {
$pass_order[] = chr(rand(48, 57));
}
for ($i = 0; $i < $other; $i++) {
$pass_order[] = chr(rand(33, 47));
}
//using shuffle() to shuffle the order
shuffle($pass_order);
//Final password string
foreach ($pass_order as $char) {
$passWord .= $char;
}
return $passWord;
}

This will help to create random password:
<?php
function generatePassword ($length = 8)
{
$genpassword = "";
$possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($genpassword, $char)) {
$genpassword .= $char;
$i++;
}
}
return $genpassword;
}
?>
<input type="text" value="<?php echo generatePassword(); ?>">

Related

Generate random 5 characters string

I want to create exact 5 random characters string with least possibility of getting duplicated. What would be the best way to do it? Thanks.
$rand = substr(md5(microtime()),rand(0,26),5);
Would be my best guess--Unless you're looking for special characters, too:
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789!##$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];
Example
And, for one based on the clock (fewer collisions since it's incremental):
function incrementalHash($len = 5){
$charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$base = strlen($charset);
$result = '';
$now = explode(' ', microtime())[1];
while ($now >= $base){
$i = $now % $base;
$result = $charset[$i] . $result;
$now /= $base;
}
return substr($result, -5);
}
Note: incremental means easier to guess; If you're using this as a salt or a verification token, don't. A salt (now) of "WCWyb" means 5 seconds from now it's "WCWyg")
If for loops are on short supply, here's what I like to use:
$s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
You can try it simply like this:
$length = 5;
$randomletter = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
more details: http://forum.arnlweb.com/viewtopic.php?f=7&t=25
A speedy way is to use the most volatile characters of the uniqid function.
For example:
$rand = substr(uniqid('', true), -5);
The following should provide the least chance of duplication (you might want to replace mt_rand() with a better random number source e.g. from /dev/*random or from GUIDs):
<?php
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$result = '';
for ($i = 0; $i < 5; $i++)
$result .= $characters[mt_rand(0, 61)];
?>
EDIT:
If you are concerned about security, really, do not use rand() or mt_rand(), and verify that your random data device is actually a device generating random data, not a regular file or something predictable like /dev/zero. mt_rand() considered harmful:
https://spideroak.com/blog/20121205114003-exploit-information-leaks-in-random-numbers-from-python-ruby-and-php
EDIT:
If you have OpenSSL support in PHP, you could use openssl_random_pseudo_bytes():
<?php
$length = 5;
$randomBytes = openssl_random_pseudo_bytes($length);
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$result = '';
for ($i = 0; $i < $length; $i++)
$result .= $characters[ord($randomBytes[$i]) % $charactersLength];
?>
I always use the same function for this, usually to generate passwords. It's easy to use and useful.
function randPass($length, $strength=8) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength >= 1) {
$consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength >= 2) {
$vowels .= "AEUY";
}
if ($strength >= 4) {
$consonants .= '23456789';
}
if ($strength >= 8) {
$consonants .= '##$%';
}
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}
It seems like str_shuffle would be a good use for this.
Seed the shuffle with whichever characters you want.
$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);
I also did not know how to do this until I thought of using PHP array's. And I am pretty sure this is the simplest way of generating a random string or number with array's. The code:
function randstr ($len=10, $abc="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789") {
$letters = str_split($abc);
$str = "";
for ($i=0; $i<=$len; $i++) {
$str .= $letters[rand(0, count($letters)-1)];
};
return $str;
};
You can use this function like this
randstr(20) // returns a random 20 letter string
// Or like this
randstr(5, abc) // returns a random 5 letter string using the letters "abc"
$str = '';
$str_len = 8;
for($i = 0, $i < $str_len; $i++){
//97 is ascii code for 'a' and 122 is ascii code for z
$str .= chr(rand(97, 122));
}
return $str
Similar to Brad Christie's answer, but using sha1 alrorithm for characters 0-9a-zA-Z and prefixed with a random value :
$str = substr(sha1(mt_rand() . microtime()), mt_rand(0,35), 5);
But if you have set a defined (allowed) characters :
$validChars = array('0','1','2' /*...*/,'?','-','_','a','b','c' /*...*/);
$validCharsCount = count($validChars);
$str = '';
for ($i=0; $i<5; $i++) {
$str .= $validChars[rand(0,$validCharsCount - 1)];
}
** UPDATE **
As Archimedix pointed out, this will not guarantee to return a "least possibility of getting duplicated" as the number of combination is low for the given character range. You will either need to increase the number of characters, or allow extra (special) characters in the string. The first solution would be preferable, I think, in your case.
If it's fine that you'll get only letters A-F, then here's my solution:
str_pad(dechex(mt_rand(0, 0xFFFFF)), 5, '0', STR_PAD_LEFT);
I believe that using hash functions is an overkill for such a simple task as generating a sequence of random hexadecimal digits. dechex + mt_rand will do the same job, but without unnecessary cryptographic work. str_pad guarantees 5-character length of the output string (if the random number is less than 0x10000).
Duplicate probability depends on mt_rand's reliability. Mersenne Twister is known for high-quality randomness, so it should fit the task well.
works fine in PHP (php 5.4.4)
$seed = str_split('abcdefghijklmnopqrstuvwxyz');
$rand = array_rand($seed, 5);
$convert = array_map(function($n){
global $seed;
return $seed[$n];
},$rand);
$var = implode('',$convert);
echo $var;
Live Demo
Source: PHP Function that Generates Random Characters
This simple PHP function worked for me:
function cvf_ps_generate_random_code($length=10) {
$string = '';
// You can define your own characters here.
$characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $string;
}
Usage:
echo cvf_ps_generate_random_code(5);
Here are my random 5 cents ...
$random=function($a, $b) {
return(
substr(str_shuffle(('\\`)/|#'.
password_hash(mt_rand(0,999999),
PASSWORD_DEFAULT).'!*^&~(')),
$a, $b)
);
};
echo($random(0,5));
PHP's new password_hash() (* >= PHP 5.5) function is doing the job for generation of decently long set of uppercase and lowercase characters and numbers.
Two concat. strings before and after password_hash within $random function are suitable for change.
Paramteres for $random() *($a,$b) are actually substr() parameters. :)
NOTE: this doesn't need to be a function, it can be normal variable as well .. as one nasty singleliner, like this:
$random=(substr(str_shuffle(('\\`)/|#'.password_hash(mt_rand(0,999999), PASSWORD_DEFAULT).'!*^&~(')), 0, 5));
echo($random);
function CaracteresAleatorios( $Tamanno, $Opciones) {
$Opciones = empty($Opciones) ? array(0, 1, 2) : $Opciones;
$Tamanno = empty($Tamanno) ? 16 : $Tamanno;
$Caracteres=array("0123456789","abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ");
$Caracteres= implode("",array_intersect_key($Caracteres, array_flip($Opciones)));
$CantidadCaracteres=strlen($Caracteres)-1;
$CaracteresAleatorios='';
for ($k = 0; $k < $Tamanno; $k++) {
$CaracteresAleatorios.=$Caracteres[rand(0, $CantidadCaracteres)];
}
return $CaracteresAleatorios;
}
I`ve aways use this:
<?php function fRand($len) {
$str = '';
$a = "abcdefghijklmnopqrstuvwxyz0123456789";
$b = str_split($a);
for ($i=1; $i <= $len ; $i++) {
$str .= $b[rand(0,strlen($a)-1)];
}
return $str;
} ?>
When you call it, sets the lenght of string.
<?php echo fRand([LENGHT]); ?>
You can also change the possible characters in the string $a.
Simple one liner which includes special characters:
echo implode("", array_map(function() {return chr(mt_rand(33,126));}, array_fill(0,5,null)));
Basically, it fills an array with length 5 with null values and replaces each value with a random symbol from the ascii-range and as the last, it joins them together t a string.
Use the 2nd array_fill parameter to control the length.
It uses the ASCII Table range of 33 to 126 which includes the following characters:
!"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Creating a random estimate string in php

I need to create a auto incrementing string similar to this randomly via php. The string is like this. So what i need is a mix of numbers and letter that is randomally generated and doesnt have to be sequential just as long as its random like this 823N9823 and it has 8 characters max
If the characters don't need to be unique:
function randomString($length = 8, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
$randomString = '';
$numofChars = strlen($chars);
while (--$length) {
$randomString .= $chars[mt_rand(0, $numofChars - 1)];
}
return $randomString;
}
If the characters must be unique:
function randomString($length = 8, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
return substr(str_shuffle($chars), 0, 8);
}
usage:
echo generateRandomName();
function:
function generateRandomName($length=8,$level=2){
list($usec, $sec) = explode(' ', microtime());
srand((float) $sec + ((float) $usec * 100000));
$validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
$validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$validchars[3] = "0123456789_!##$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!##$%&*()-=+/";
$password = "";
$counter = 0;
while ($counter < $length) {
$actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);
// All character must be different
if (!strstr($password, $actChar)) {
$password .= $actChar;
$counter++;
}
}
return $password;
}
Found on PHPToys
Level the level of characters to be used, 3 have special chars as $validchars[3] has.
You also can call it as: generateRandomName(5) to generate a name with length of 5.
function generateRandomString($length=8, $characters='abcdefghijklmnopqrstuvwxyz0123456789'){
$str = '';
$len = strlen($characters);
for($i=0; $i<length; $i++){
$str .= $characters[mt_rand(0, $len)];
}
return $string;
}
Usage:
//generates a random string, using defaults: length = 8 and characters = a-z, 0-9
echo "Your password: " . generateRandomString();
//custom length: 10
echo "Thingeys: " . generateRandomString(10);
//digits only, length 4
echo "Your PIN: " . generateRandomString(4, '0123456789');
You can use mt_rand() to generate a random integer and then transform the values into a string. The function below will give you 2 821 109 907 456 possible values.
function random_id($length = 8) {
$validChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$rndString = '';
for($i = 0; $i < $length; $i++) {
$rndString .= $validChars[mt_rand(0, strlen($validChars) - 1)];
}
return $rndString;
}
$lengthEight = random_id();
$lengthTen = random_id(10);
Since there are more letters and numbers in the list of possible characters, you'll usually get a string with more letters then numbers.
If you want to skew the results towards a string with more numbers then letters, then you can use the following:
function skewed_random_id($numericFactor = 0.8, $length = 8) {
$validAlpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$validNumeric = '0123456789';
$rndString = '';
for($i = 0; $i < $length; $i++) {
if((mt_rand() / mt_getrandmax()) < $numericFactor) {
$rndString .= $validNumeric[mt_rand(0, strlen($validNumeric) - 1)];
} else {
$rndString .= $validAlpha[mt_rand(0, strlen($validAlpha) - 1)];
}
}
return $rndString;
}
$eightyPercentNumeric = skewed_random_id();
$fiftyFifty = skewed_random_id(0.5);
$allAlpha = skewed_random_id(0);
$allNumeric = skewed_random_id(1);
echo substr(str_replace(array('/', '+'), '', base64_encode(sha1(uniqid(), true))), 0, 8);
Sample output:
LTeQpy9p
v11oy9R7
TjdkXZru
lh3TvNi4
X5Ca0ZXS
L01RfhxW
QDfwNnGO
you can use strtoupper and strtolower to get a version that suits your needs.
EDIT:
If you are gonna use this for something critical rather than just wanting a random string, change uniqid() into mt_rand():
echo substr(str_replace(array('/', '+'), '', base64_encode(sha1(
mt_rand(). '.'. mt_rand(). '.'. mt_rand()%4 //256^8 of input possibilities (8 bytes)
, true))), 0, 8);
substr(uniqid(), 0, 8);
http://php.net/uniqid

Auto incrementing unique url

I am looking to create an auto incrementing unique string using PHP, containing [a-Z 0-9] starting at 2 chars long and growing when needed.
This is for a url shrinker so each string (or alias) will be saved in the database attached to a url.
Any insight would be greatly appreciated!
Note this solution won't produce uppercase letters.
Use base_convert() to convert to base 36, which will use [a-z0-9].
<?php
// outputs a, b, c, ..., 2o, 2p, 2q
for ($i = 10; $i < 99; ++$i)
echo base_convert($i, 10, 36), "\n";
Given the last used number, you can convert it back to an integer with intval() increment it and convert the result back to base 36 with base_convert().
<?php
$value = 'bc9z';
$value = intval($value, 36);
++$value;
$value = base_convert($value, 10, 36);
echo $value; // bca0
// or
echo $value = base_convert(intval($value, 36) + 1, 10, 36);
Here's an implementation of an incr function which takes a string containing characters [0-9a-zA-Z] and increments it, pushing a 0 onto the front if required using the 'carry-the-one' method.
<?php
function incr($num) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$parts = str_split((string)$num);
$carry = 1;
for ($i = count($parts) - 1; $i >= 0 && $carry; --$i) {
$value = strpos($chars, $parts[$i]) + 1;
if ($value >= strlen($chars)) {
$value = 0;
$carry = 1;
} else {
$carry = 0;
}
$parts[$i] = $chars[$value];
}
if ($carry)
array_unshift($parts, $chars[0]);
return implode($parts);
}
$num = '0';
for ($i = 0; $i < 1000; ++$i) {
echo $num = incr($num), "\n";
}
If your string was single case rather than mixed, and didn't contain numerics, then you could literally just increment it:
$testString="AA";
for($x = 0; $x < 65536; $x++) {
echo $testString++.'<br />';
}
$testString="aa";
for($x = 0; $x < 65536; $x++) {
echo $testString++.'<br />';
}
But you could possibly make some use of this feature even with a mixed alphanumeric string
To expand on meagar's answer, here is how you can do it with uppercase letters as well and for number arbitrarily big (requires the bcmath extension, but you could as well use gmp or the bigintegers pear package):
function base10ToBase62($number) {
static $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$result = "";
$n = $number;
do {
$remainder = bcmod($n, 62);
$n = bcdiv($n, 62);
$result = $chars[$remainder] . $result;
} while ($n > 0);
return $result;
}
for ($i = 10; $i < 99; ++$i) {
echo base10ToBase62((string) $i), "\n";
}

PHP Random Number

I want to generate a random number in PHP where the digits itself should not repeat in that number.
Is that possible?
Can you paste sample code here?
Ex: 674930, 145289. [i.e Same digit shouldn't come]
Thanks
Here is a good way of doing it:
$amountOfDigits = 6;
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $amountOfDigits;$i++)
$digits .= $numbers[$i];
echo $digits; //prints 217356
If you wanted it in a neat function you could create something like this:
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
function randomize($len = false)
{
$ints = array();
$len = $len ? $len : rand(2,9);
if($len > 9)
{
trigger_error('Maximum length should not exceed 9');
return 0;
}
while(true)
{
$current = rand(0,9);
if(!in_array($current,$ints))
{
$ints[] = $current;
}
if(count($ints) == $len)
{
return implode($ints);
}
}
}
echo randomize(); //Numbers that are all unique with a random length.
echo randomize(7); //Numbers that are all unique with a length of 7
Something along those lines should do it
<?php
function genRandomString() {
$length = 10; // set length of string
$characters = '0123456789'; // for undefined string
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$s = genRandomString(); //this is your random print var
or
function rand_string( $length )
{
$chars = "0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$str .= $chars[ rand( 0, $size – 1 ) ];
}
return $str;
}
$rid= rand_string( 6 ); // 6 means length of generate string
?>
$result= "";
$numbers= "0123456789";
$length = 8;
$i = 0;
while ($i < $length)
{
$char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1);
//prevents duplicates
if (!strstr($result, $char))
{
$result .= $char;
$i++;
}
}
This should do the trick. In $numbers you can put any char you want, for example: I have used this to generate random passwords, productcodes etc.
The least amount of code I saw for something like this was:
function random_num($n=5)
{
return rand(0, pow(10, $n));
}
But I'm assuming it requires more processing to do this than these other methods.

Generating (pseudo)random alpha-numeric strings

How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
First make a string with all your possible characters:
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
You could also use range() to do this more quickly.
Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:
$string = '';
$max = strlen($characters) - 1;
for ($i = 0; $i < $random_string_length; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
$random_string_length is the length of the random string.
I like this function for the job
function randomKey($length) {
$pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));
for($i=0; $i < $length; $i++) {
$key .= $pool[mt_rand(0, count($pool) - 1)];
}
return $key;
}
echo randomKey(20);
Generate cryptographically strong, random (potentially) 8-character string using the openssl_random_pseudo_bytes function:
echo bin2hex(openssl_random_pseudo_bytes(4));
Procedural way:
function randomString(int $length): string
{
return bin2hex(openssl_random_pseudo_bytes($length));
}
Update:
PHP7 introduced the random_x() functions which should be even better. If you come from PHP 5.X, use excellent paragonie/random_compat library which is a polyfill for random_bytes() and random_int() from PHP 7.
function randomString($length)
{
return bin2hex(random_bytes($length));
}
One line solution:
echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );
You can change the substr parameter in order to set a different length for your string.
Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
See More:
chr function
mt_rand function
I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:
class RandomString
{
private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
private static $string;
private static $length = 8; //default random string length
public static function generate($length = null)
{
if($length){
self::$length = $length;
}
$characters_length = strlen(self::$characters) - 1;
for ($i = 0; $i < self::$length; $i++) {
self::$string .= self::$characters[mt_rand(0, $characters_length)];
}
return self::$string;
}
}
Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.
$str = bin2hex(random_bytes(32)); // 64 character string returned
Maybe I missed something here, but here's a way using the uniqid() function.
I have made the following quick function just to play around with the range() function. It just might help someone sometime.
Function pseudostring($length = 50) {
// Generate arrays with characters and numbers
$lowerAlpha = range('a', 'z');
$upperAlpha = range('A', 'Z');
$numeric = range('0', '9');
// Merge the arrays
$workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));
$returnString = "";
// Add random characters from the created array to a string
for ($i = 0; $i < $length; $i++) {
$character = $workArray[rand(0, 61)];
$returnString .= $character;
}
return $returnString;
}
You can use the following code. It is similar to existing functions except that you can force special character count:
function random_string() {
// 8 characters: 7 lower-case alphabets and 1 digit
$character_sets = [
["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
["count" => 1, "characters" => "0123456789"]
];
$temp_array = array();
foreach ($character_sets as $character_set) {
for ($i = 0; $i < $character_set["count"]; $i++) {
$random = random_int(0, strlen($character_set["characters"]) - 1);
$temp_array[] = $character_set["characters"][$random];
}
}
shuffle($temp_array);
return implode("", $temp_array);
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
echo generateRandomString();
If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:
substr( sha1( time() ), 0, 15 )
time() gives you the current time in seconds since epoch, sha1() encrypts it to a string of 0-9a-f, and substr() lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.
First list the desired characters
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Use the str_shuffle($string) function. This function will provide you a randomly shuffled string.
$alpha=substr(str_shuffle($chars), 0, 50);
50 is the Length of string.
This is something I use:
$cryptoStrong = true; // can be false
$length = 16; // Any length you want
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
$randomString = bin2hex($bytes);
You can see the Docs for openssl_random_pseudo_bytes here, and the Docs for bin2hex here
Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().
<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$string = "";
for($i = 0; $i < 6; $i++) {
$string .= $character_array[rand(0, (count($character_array) - 1))];
}
echo $string;
?>
This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().
1 line:
$FROM = 0; $TO = 'zzzz';
$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);
echo $code;
The modern way to do that with type hint / rand_int for real randomeness
function random_string(int $size): string
{
$characters = array_merge(
range(0, 9),
range('A', 'Z')
);
$string = '';
$max = count($characters) - 1;
for ($i = 0; $i < $size; $i++) {
$string .= $characters[random_int(0, $max)];
}
return $string;
}
public function randomString($length = 8)
{
$characters = implode([
'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',
'abcdefghijklmnoprqstuwvxyz',
'0123456789',
//'!##$%^&*?'
]);
$charactersLength = strlen($characters) - 1;
$string = '';
while ($length) {
$string .= $characters[mt_rand(0, $charactersLength)];
--$length;
}
return $string;
}

Categories