PHP Classes

File: example.php

Recommend this page to a friend!
  Classes of Francesco Cirać   Token   example.php   Download  
File: example.php
Role: Example script
Content type: text/plain
Description: Example script
Class: Token
Generate and check tokens to avoid CSRF attacks
Author: By
Last change:
Date: 14 years ago
Size: 1,366 bytes
 

Contents

Class file image Download
<?php
// Example of a page protected from Session Riding (CSRF) by Token.

// Including Token class file
include_once "token.class.php";
// Getting an istance of Token; the new token will be created here.
$T = new Token(2); // We choose, in this example, two minutes of timeout for our tokens. In a true website, two minutes will be not enough, probably.

// Now, We'll check how the situation is.
// The Check method returns true if the request token is right; false otherwise.
// Obviously, if the page is not supposed to be protected, the return value of Check doesn't matters to you!

if($T->Check()) { // If Check goes right, the page have got the right token.
   
echo "Allright, the token is fine!";
}
else {
// Else, there is some error..
    // We can catch the error with the Error method.
    // It returns an integer error code; see the documentation to find out the meanings of the various codes.
   
switch($T->Error()) {
        case
1: { echo "No Request Token detected."; break; }
        case
2: { echo "No Session Token corrisponding to the Request Token."; break; }
        case
3: { echo "No value for the Session Token."; break; }
        case
4: { echo "Token reached the timeout."; break; }
    }
}
// Now, let's print a link to this page using the token!
echo "<br /><a href=\"".$T->protectLink("example.php")."\">Retry using the session token!</a>";
?>