Thursday, 9 August 2018

Secure PHP Logout Script.

This is a short PHP tutorial on how to create a simple user logout script that guards against CSRF attacks.

CSRF attack.

In case you didn’t already know, CSRF stands for Cross-Site Request Forgery, which is a type of attack that tricks unsuspecting users into doing something that they didn’t intend on doing.
In the context of our logout system, such an attack could be used to trick unsuspecting users into logging out of the website.

Example.

Let’s take a look at the following example, which assumes that your logout script is located at logout.php:
The HTML link above will look like a link to Google’s website. However, if an unsuspecting user clicks on it, they will logged out of the system.

Session token.

When the user logs into your website, you should provide them with a cryptographically secure token. This token can then be used to validate certain actions and guard against CSRF attacks.
An example of what you might have in your login script:
In the PHP code above, we created a token and assigned it to a session token.

Our logout link.

The HTML link to out PHP logout script should look something like this:
As you can see, the secure token that we gave the user when they logged into our system has been appended to the link in the form of a GET parameter called “token”.
Clicking on such a link will lead to a URL such as:
logout.php?token=27b87f10bb05279a749f19396b34d9550e7945213bec9d36
This will let our PHP logout script know what token was being used when the user clicked on the logout button.

Our PHP logout script.

Finally, in our PHP logout script, we validate the token in the query string by comparing it against the token that is stored in the user’s session:
If the token is valid, we destroy the user’s session using PHP’s session_destroy function. This particular function will destroy all data that is registered to a session. If the token is invalid, then nothing happens and the user is not logged out.

0 comments:

Post a Comment