Page 1 of 1

Automatic Expiry of the Code - PHP

Posted: Fri Sep 19, 2008 10:29 pm
by everurssantosh
Hi,

I am trying to create an Authorization code for a user which should automaticaly get expired after 15 mins of generation.

I am using PHP rand function to generate the code. This code will be sent to user by mail. Now, user must use the code with in 15 mins in some other page.

The problem : how to I delete the code after 15 mins, though I save the time of generation of the code.

Please help me in this regard


Santosh

Re: Automatic Expiry of the Code - PHP

Posted: Fri Sep 19, 2008 11:09 pm
by murp3433
everurssantosh wrote:Hi,

I am trying to create an Authorization code for a user which should automaticaly get expired after 15 mins of generation.

I am using PHP rand function to generate the code. This code will be sent to user by mail. Now, user must use the code with in 15 mins in some other page.

The problem : how to I delete the code after 15 mins, though I save the time of generation of the code.

Please help me in this regard


Santosh
if you are using a database backend you could create a timestamp field and only validate the code if it it was used within 15 min of creation

Re: Automatic Expiry of the Code - PHP

Posted: Sat Sep 20, 2008 3:54 pm
by daniel142005
Heres a sample way of how to do this with php/mysql.

First, create a table in your mysql database... I'll just use "codes" as an example. Give the table at least 3 fields

CodeID - The unique ID, autoincrementing and primary.
Code - The actual code
Date - The time the code was generated

Sample table creation code:

Code: Select all

CREATE TABLE `codes` (
`CodeID` INT( 200 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`Code` TEXT NOT NULL ,
`Date` INT( 150 ) NOT NULL
) ENGINE = InnoDB
To add a code:

Code: Select all

 
$date = mktime(); // Get the date/time
$code = substr(md5($date), 0, 10); // Generate the code
$sql = "INSERT INTO `codes` (`Code`, `Date`) VALUES ('$code', '$date');";
mysql_query($sql);
 
Once the code has been added you will need to have a way to make it autoclear after 15 min. When I need to do this I simply add a line of code to every page to handle it. Something like:

Code: Select all

 
$sql = "SELECT * FROM `codes`;";
$que = mysql_query($sql);
while($aso = mysql_fetch_assoc($que)) // Loop through all the codes
{
    $date = $aso['Date']; // Get the current code's date
    if($date + (15*60) > mktime()) // Compare the codes, if the current one + 15 min is greater than the current time, delete it.
    {
         mysql_query("DELETE FROM `codes` WHERE `CodeID` = '{$aso['CodeID']}';"); // Delete it
    }
}
 
You will probably need a way to link the code to the account, you can do this by adding a field that links to the account ID in this table, or by adding a field in your user table that links to the code. I also have the above code in a function to reduce the lines on the page and just include it to all the other pages. Hope this helps.

Daniel