Jump to content
xisto Community
Sign in to follow this  
szupie

Php Random Text Generating How to Generate Random Text

Recommended Posts

I was trying to figure out how to make random texts for random passwords and stuff, and I found someone who created this code.

<?
//author: polmme

$codelenght = 10;
while($newcode_length < $codelenght) {
$x=1;
$y=3;
$part = rand($x,$y);
if($part==1){$a=48;$b=57;}  // Numbers
if($part==2){$a=65;$b=90;}  // UpperCase
if($part==3){$a=97;$b=122;} // LowerCase
$code_part=chr(rand($a,$;));
$newcode_length = $newcode_length + 1;
$newcode = $newcode.$code_part;
}
echo $newcode;
?>


I think it's pretty good. If anyone has a better one or suggestions, please tell me.

Share this post


Link to post
Share on other sites

Well the only real way to work out whether it's good or not is to work out it's logic, yet I'm not in the mood for testing my brain, so I'll just rewrite this example in a different way but still same ending results, oh and I'll fix those notice errors for those undeclared variables.

 

Sorry to the author polmme it was a nice example indeed and a lot simpler to understand for beginners than my rewrite I admit.

 

<?php

for($code_length = 10, $newcode = ''; strlen($newcode) < $code_length; $newcode .= chr(!rand(0, 2) ? rand(48, 57) : (!rand(0, 1) ? rand(65, 90) : rand(97, 122))));

 

echo $newcode;

?>

 

I also have one I made based off someone elses code but I lost who that was, anyways here it is. I should have turned it into a function (just did), I know there was more I was going to do, which was randomise the characters within $salt string (just did) as well but didn't continue on this (just did), I might add to it later (just did), I got to be somewhere 5 minutes ago (just got back) ;) What my intensions were, was to actually take a section from the string (just did) and use that as the password, as there really is no need to keep randomising it and then randomise again, and then do another randomise, although we could keep this going (stopped before this).

 

<?php

function mkRandPasswd()

{

define('NUM0', 48);

define('NUM9', 57);

define('LETA', 65);

define('LETZ', 90);

define('LETa', 97);

define('LETz', 122);

$salt = '';

$passwd = '';

 

define('PASSWD_LEN', 10);

 

for($nLoop = 0; $nLoop < NUM9 - NUM0 + 1; $nLoop++)

$salt .= chr(mt_rand(NUM0, NUM9));

for($ucLoop = 0; $ucLoop < LETZ - LETA + 1; $ucLoop++)

$salt .= chr(mt_rand(LETA, LETZ));

for($lcLoop = 0; $lcLoop < LETz - LETa + 1; $lcLoop++)

$salt .= chr(mt_rand(LETa, LETz));

 

$salt = str_shuffle($salt);

 

for($gen = 0; $gen < PASSWD_LEN; $gen++)

$passwd = $passwd . substr($salt, mt_rand() % strlen($salt), 1);

 

return array($salt, $passwd);

}

 

list($salt, $passwd) = mkRandPasswd();

 

$str_passwd = substr($salt, strlen($salt) / 4, PASSWD_LEN);

 

echo 'Characters to select for password: ' . $salt . '<br /> The generated password: ' . $passwd . '<br /> The stringed password: ' . $str_passwd;

 

?>

 

Remember not much can be said about the script unless the logic is worked out, I still haven't worked mine out, but I can say it's safe enough for password generating, you still would require the user to change the password and not keep it.

 

 

Cheers,

 

 

MC

Share this post


Link to post
Share on other sites

Interesting, I just made a random text generator, its located on my site. This code however generates only random letters between 4-7 characters long. The code is pretty simple:

for($j = 1; $j <= 30; $j++)  {    $lim = rand(4,7);    for ($i = 1; $i <= $lim; $i++)    {      echo chr(ord('a') + rand(0,25));    }    echo "<BR>\n";  }

Hope this is useful.

Share this post


Link to post
Share on other sites

another way would to make a table with all the allowed signsa,b,c,d,... ,A,B,C,D,... 1,2,3,...let's say you get a table of 80 fields.then you could just pick a random fieldyou could do this in various way: just rand(0,80)if you have doubts about the randomness of rand, you could rand a random times and then start picking your letters$i = rand(0,20);for ($j=0; $j<$i;$j++) rand(0,80);for ($i=0; $i<$passlenght;$i++) $pw =$pw.$array[rand(0,80)];or you could use srandor you could go like rand(0,846854354)%80anything that makes you feel safer :P

Share this post


Link to post
Share on other sites

Ya know what you could just do is be sneaky and do this.

$ranNum = rand(100,9999).'-'.Rand(10000,999999);

$hexRan = md5($ranNum );

ThisConverts it to a MD5 Hash and since its random it doesn't reallyMatter. Store it in the DB and you should be good. Of course this codeIs only good if you want to have letters and numbers in the string. IfYou're going for JUST text, well then I would suggest doing somethingLike what is described above.

Share this post


Link to post
Share on other sites

To generate some random characters I use a bit different method, it might be slower, but if it's for a personal site or a site not as big as Wikipedia you can use this code, even though it's not as slow as you can imagine, it works normally and in my opinion is a bit more clear to people who will start editing it:

function gen_chars($length = 6) {	// Available characters	$chars = '0123456789abcdefghjkmnoprstvwxyz';	$Code  = '';	// Generate code	for ($i = 0; $i < $length; ++$i)	{		$Code .= substr($chars, (((int) mt_rand(0,strlen($chars))) - 1),1);	}return $Code;}// Usage$var = gen_chars(12);echo $var;

In the function variable $chars = '..'; I did not include all the letters, because I use this function for sending SMS code to activate some feature on a site and some letters does not feet, due to they look similar, like l can look like 1 and etc. if they are one to another, of course if you'll add all the alphabet and maybe even other symbols and even uppercase letters you'll get a much bigger probability for it to be different for example looping it million times and of course making more than 6 or 12 characters/length will have more different variations. :D

Share this post


Link to post
Share on other sites
How to generate a group of word from CharactersPhp Random Text Generating

I want to a making a word from group of the character.Eg. Opinion is a correct word from the group of character ionnipo(generate a group of the word in php from 7 character)

-reply by musavvir

Share this post


Link to post
Share on other sites

Really simple one here for ya, works just fine however no letter or number is repeated (will be in the next example):

$alphanum = "abcdefghijkmnpqrstuvwxyz23456789";      $rand = substr(str_shuffle($alphanum), 0, 5);  // 5 Being the amount of letters/numbers are select from the variable alphanum

And if you want letters and numbers to have a chance of being repeated:

$alphanum = "abcdefghijkmnpqrstuvwxyz23456789";      $inc = 1;   while ($inc < 5){   $alphanum = $alphanum.'abcdefghijkmnpqrstuvwxyz23456789';   $inc++;   }        $rand = substr(str_shuffle($alphanum), 0, 5);  // 5 Being the amount of letters/numbers are select from the variable alphanum


And finally for a random length text string with possible repeated letters or numbers:

$alphanum = "abcdefghijkmnpqrstuvwxyz23456789";      $inc = 1;   while ($inc < 5){   $alphanum = $alphanum.'abcdefghijkmnpqrstuvwxyz23456789';   $inc++;   }        $rand = substr(str_shuffle($alphanum), 0, rand(3,10));  // 3 Being the minimum amound of letters returned and 10 being the maximum

Edited by 8ennett (see edit history)

Share this post


Link to post
Share on other sites

The iGuest way which you prefer has one bad thing, that it's using md5, which you can substr or something to make it use less symbols, but the problem then is that you're stuck only with these letters:abcdef1234567890where with my method and 8ennett method you can include anything you want, even #$%^ symbols, which can be good for a CAPTCHA or for a SMS code or for any code which needs to be short and have a lot of different variations to not generate the same.Those long codes which are lets say 16 letters are good for generating confirmation codes, where you don't really care about it, those kind of codes usually are copied and pasted or clicked on. ;)

Share this post


Link to post
Share on other sites
Complete SolutionPhp Random Text Generating

<?php/** * @author Praateek * @copyright 2010 */$randcheck = rand(0, 4);   if ($randcheck == 0)   {   $custom = chr(ord("a") + rand(0, 25)) . Rand(10, 99) . Chr(ord("a") + rand(0, 25)) .   rand(10, 99);   } elseif ($randcheck == 1)   {   $custom = rand(10, 99) . Chr(ord("a") + rand(0, 25)) . Rand(10, 99) . Chr(ord("a") +   rand(0, 25));   } elseif ($randcheck == 2)   {   $custom = chr(ord("a") + rand(0, 25)) . Chr(ord("a") + rand(0, 25)) . Rand(10, 99) .   rand(10, 99);   } elseif ($randcheck == 3)   {   $custom = rand(10, 99) . Rand(10, 99) . Chr(ord("a") + rand(0, 25)) . Chr(ord("a") +   rand(0, 25));   } elseif ($randcheck == 4)   {   $custom = rand(10, 99) . Chr(ord("a") + rand(0, 25)) . Chr(ord("a") + rand(0, 25)) .   rand(10, 99);   }   echo $custom;?>

Share this post


Link to post
Share on other sites
This is the best i got online, try it..Php Random Text GeneratingGenerate random passwords with PHP In this tutorial I will show you how to generate random passwords that are highly secure and extremely difficult to crack. However you can choose between various complexity/strength and you can set password length as well. Step 1. Let’s go through what we need to generate passwords. First we need a list of words and/or characters what we can use for password generation. I don’t offer using word lists as it is easier to guess and password recovery tools are using such lists as well. So I will focus only on character lists. The idea is to create a string from the characters and than in a loop we select an item from this string (character list) one by one until we reach the requested length. To realize this we will implement a function with 2 parameters. The first is the length of the requested password and the second is the strength/complexity of the password. Step 2. The function use case looks like this: Initializing the PHP random generator using the actual time value. Define 3 variousstrings for the various password complexity. Reset the password andlength counter variables Create a loop until the requested length andappend a random character one by one to the password string. In the loop I made one more check to make all character different in the generatedpassword. Return with the ready password.It is quite simple and you can generate really strong passwords with it. The complete code looks like this:<?phpfunction generatePassword($length=6,$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;}?>Step 3. To make the script more usable let’s create an html page where the visitor can set the requested length and strength of the password. To do this we will create a simple form with 2 drop down box where the visitor can select the password properties. In this example I set the length list from 5 to 10 and the strength to Easy, Normal, and Hard. When the visitor submits the form it will call itself and in this phase not only shows the form again but processes the submitted values and generates the requested password and shows it for the user. The HTML code is quite simple: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.Dtd"><html><body> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table> <tr><td>Password length: </td><td> <select name="passlength"> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> </td></tr> <tr><td>Password strength:</td><td> <select name="passstrength"> <option value="1">Easy</option> <option value="2">Normal</option> <option value="3">Hard</option> </select> </td></tr> <tr><td ><br/><input type="submit" name="submitBtn" value="Generate"></td></tr> </table> </form><?php if (isset($_POST['submitBtn'])){ echo '<table><tr><td>Generated password:</td><td>'; echo generatePassword($length,$strength); echo '</td></tr></table>'; }?></body> Step 4. Final words:As you can see generating a random password is not so complex task. You can integrate this script into your registration process to generate a password for the user. The complete script is the following:<?phpfunction generatePassword($length=6,$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;}?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.Dtd"><html><body> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table> <tr><td>Password length: </td><td> <select name="passlength"> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> </td></tr> <tr><td>Password strength:</td><td> <select name="passstrength"> <option value="1">Easy</option> <option value="2">Normal</option> <option value="3">Hard</option> </select> </td></tr> <tr><td ><br/><input type="submit" name="submitBtn" value="Generate"></td></tr> </table> </form><?php if (isset($_POST['submitBtn'])){ echo '<table><tr><td>Generated password:</td><td>'; echo generatePassword($length,$strength); echo '</td></tr></table>'; }?></body> -reply by James Bondze

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.