> > Generating random alphanumeric characters in php

Generating random alphanumeric characters in php

Posted on Friday 17 August 2012 | No Comments

Random alphanumeric characters may be used in many parts of a script such as renaming an uploaded file or creating a user registration validation mailing system.

In this script, all you need to do is to just specify the length of the alphanumeric characters and they'll be generated.

I wanted to use this script in my image upload system which could rename the image uploaded by user. But before chasing the Internet, I thought to create my own script. So I started programming this script. And here's the result what I programmed:

<?php

function random_name(){

$CapAlphas = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

$smallAlphas = array("z", "y", "x", "w", "v", "u", "t", "s", "r", "q", "p", "o", "n", "m", "l", "k", "j", "i", "h", "g", "f", "e", "d", "c", "b", "a");

$thestring =  $CapAlphas[rand(0, 26)];
$thestring .= $smallAlphas[rand(0, 26)];
$thestring .= rand(0, 9);
$thestring .= $CapAlphas[rand(0, 26)];
$thestring .= $smallAlphas[rand(0, 26)];
$thestring .= $CapAlphas[rand(0, 26)];
$thestring .= $smallAlphas[rand(0, 26)];
$thestring .= $smallAlphas[rand(0, 26)];
$thestring .= rand(0, 9);
$thestring .= rand(0, 9);
$thestring .= $smallAlphas[rand(0, 26)];
$thestring .= $CapAlphas[rand(0, 26)];
$thestring .= rand(0, 9);
$thestring .= $smallAlphas[rand(0, 26)];
$thestring .= $CapAlphas[rand(0, 26)];

return $thestring;

}//end function random_name()

echo random_name();

?> 
Yes, I know this script is very long and works on a complicated logic.
There's an array of small and capital alphabets and then the arrays are instantiated with random indexes and some random numbers in between.

I'll update this post when I get a perfect way of doing so.

If you have any questions or modifications in the script or any other technique, please share in comments.

Leave a Reply

Powered by Blogger.