How to Create a Random Key Gen. in PHP
by GrooN
This is a tutorial on how to create a simple keygen, that generates keys with random characters (a-z, A-Z and 0-9).
First off we're going to create the HTML code.
I dont know why, we have to start somewhere.
Okay, you should know HTML, but im gonna explain it anyway.Code:<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>"> Colums: <input type="text" name="colums" /><br /> Rows: <input type="text" name="amount" /><br /> <input type="submit" /> </form>
Here we're making a <form>, that makes it possible for us to send information from the user to the php script.
Sets the method to get, and the action to $_SERVER['PHP_SELF'] (which returns the name of the current file.)
Now, here comes the php part:
Now that should be that hard to understand:PHP Code:
<?php
if ($_REQUEST['columns'] && $_REQUEST['amount'])
{
$library = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321";
for ($i = 0; $i < $_REQUEST['columns']; $i++) // Loop one
{
for ($in = 0; $in < $_GET['amount']; $in++) // Loop two
$return .= $library[rand(0, strlen($library))]; // Takes random char from the library string.
if ($i < ($_REQUEST['columns'] - 1)) // Set the '-' tag between every column
$return .= "-";
}
echo $return; // Print result
}
?>
first we see if the server has received the information sent from the form, by using the $_REQUEST[], which receives both GET and POST.
Then we declare a library string, that contains all the possible characters, that the keygen are going to write.
After that i create a for loop, that repeats itself as many times the variable $_REQUEST['columns'] says it.
Then i make yet another for loop inside that one where i do the same just with the $_REQUEST['amount'] variable.
Inside that for loop, we write to the "$return" variable. We write a random character from the library string, by using the function rand(min, max).
When that second for loop ends the script adds a "-" tag if its not the last time it runs.
At last we write the result by using the echo as you learned when you read some, hello world tutorial
Mixing the two blocks of code, it should look like this:
Dont be afraid to ask questions ^^Code:<?php if ($_REQUEST['columns'] && $_REQUEST['amount']) { $library = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321"; for ($i = 0; $i < $_REQUEST['columns']; $i++) // Loop one { for ($in = 0; $in < $_GET['amount']; $in++) // Loop two $return .= $library[rand(0, strlen($library))]; // Takes random char from the library string. if ($i < ($_REQUEST['columns'] - 1)) // Set the '-' tag between every column $return .= "-"; } echo $return; // Print result } ?> <form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>"> Colums: <input type="text" name="colums" /><br /> Rows: <input type="text" name="amount" /><br /> <input type="submit" /> </form>