Get complete CodeIgniter blog project for free!

Downloaded more than 161 times, this is full project must-study for serious developers!

By submitting this form, you agree to our Terms of Service and Privacy Policy.

Random code generator in PHP

PHP always helps us to create something new always. Today we are going to create a new function name as Random code generator using php. The random code generator is mainly a program which helps to create random code in every time. It helps you to create a different code for session or confirmation code. Let’s see how we can create this function. We are going to this code using php. First, we create a function rand_code() and put some code for this function. But here is a trick, we can create our random code with using any length. For that, we will pass a variable for that. In this fact our function will rand_code($length). We pass length as our wish then this function will run the random code a specific length which is provided by us.
Our function is

function rand_code($len)
{
$min_lenght= 0;
$max_lenght = 100;
$bigL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$smallL = "abcdefghijklmnopqrstuvwxyz";
$number = "0123456789";
$bigB = str_shuffle($bigL);
$smallS = str_shuffle($smallL);
$numberS = str_shuffle($number);
$subA = substr($bigB,0,5);
$subB = substr($bigB,6,5);
$subC = substr($bigB,10,5);
$subD = substr($smallS,0,5);
$subE = substr($smallS,6,5);
$subF = substr($smallS,10,5);
$subG = substr($numberS,0,5);
$subH = substr($numberS,6,5);
$subI = substr($numberS,10,5);
$RandCode1 = str_shuffle($subA.$subD.$subB.$subF.$subC.$subE);
$RandCode2 = str_shuffle($RandCode1);
$RandCode = $RandCode1.$RandCode2;
if ($len>$min_lenght && $len<$max_lenght)
{
$CodeEX = substr($RandCode,0,$len);
}
else
{
$CodeEX = $RandCode;
}
return $CodeEX;
}
This is our function, we can customize this function as our requirement. $min_lenght and $max_lenght variables help us to execute minimum and a maximum start point of random code. We can config this before using as our requirement. When we run this function with length like

<?php
echo rand_code(10);
?>
Then this function will execute different code in every time. We can use this code for a set user session, send verification code using this code. I hope this code is helpful for us.





Search on PHPAns
Subscribe to PHPAns
Join with our 32000+ subscribers and get our latest articles in your email inbox for free.
Delivered by FeedBurner
We always respect your privacy and take protecting it seriously.
Connect Social With PHPAns
Top