09 November, 2010

How to expire a link using php

Once i got a problem of how to expire a link after it is clicked once using php. My situation was,
i had to send some confirmation link email to users, and when a user clicked the confirm link then
it should be set as expired, i mean, clicking on it for second time (more than once) should not
execute a function, i.e it should act as a dead link when clicked once.
So for this problem, i used hash trchnique of php.
Here is what i did to expire link that is clicked once.
Step 1:
I created a hash using some secret and email address of user, as:

$secret = "234234456jbkjkbkj2b34kj2b4";
//the secret can be defined somewhere in the file or same function
$emailAdd = "john@doe.com";
//create a hash from this
$ourhash = sha1($secret.$emailAdd);
//store this hash in database

This created a unique hash, since email addresses are unique
Step 2:
Add the hash that we created in Step 1 to the confirm link,
that is to be sent to email, as,

$emailBody = 'This is a test.......';
$emailBody = 'Please click Confirm to proceed..!';

Now the hash is appened to the confirm link in email message.
Strp 3:
In somefunction.php file, check the hash in the link with ours,
since we know the email address and hash, we can do as,

//get the stored hash for $userId from database
$ourHash = $hashFromDb;
//now check this with the hash in url
$hashFromUrl = $_GET["hash"];
if($ourHash == $hashFromUrl) {
//update database or do some actions here
//delete the hash
}
else {
echo "This link in not valid.";
}

And thats it. I have done this in my own way, this has to be cleaned and securified
more, i think. But i hope this helps someone like me to startup.

No comments: