Search code examples
phpajaxformssecuritytoken

Form token, to prevent direct access, does not work


I want to use a token to secure my pages which are loaded via an AJAX-request (the basic idea is to prevent direct access of that page). So far so good.

The problem is that both tokens do not match. It doesn't work.

To create my token I use this function:

function generateFormToken($form) {
$token = md5(uniqid(microtime(), true));

$_SESSION[$form.'_token'] = $token;

return $token;
}

To verify them I use this function:

function verifyFormToken($form) {
if (!isset($_SESSION[$form.'_token'])) {
    return false;
}

if(!isset($_POST['token'])) {
    return false;
}

if ($_SESSION[$form.'_token'] !== $_POST['token']) {
    return false;
}

return true;
}

In my form contact_form.php I create my token:

$newToken = generateFormToken('contactForm');

Then I put that generated token into a hidden field:

<input type="hidden" name="token" value="<?php echo $newToken; ?>" />

In my header of my website I start a session:

if (session_id() === '') {
    session_start();
}

The reason why I'm checking if there's already another session is because on my index.php-page there's a cookie set (without the check I get a PHP-error message saying that there's already a session):

if (isset($_COOKIE['ava_lastpage'])) {
$prev_page = secure($_COOKIE['ava_lastpage']);
}
// Set current page
if (!isset($_GET['task']) || (isset($_GET['task']) && $_GET['task'] != 'register' && $_GET['task'] != 'validate' && $_GET['task'] != 'login' && !isset($_GET['status']) || isset($_GET['status']) && $_GET['status'] != 'reg_complete')) {
setcookie('ava_lastpage', curPageUrl(), time()+60*60*24*100, '/');
}

This is my AJAX-request (contact.php is the file that shall be protected via a token):

$.ajax({
type:'POST',
url: '<?php echo $setting['site_url'] .'/';?>includes/misc/contact.php',
data:$('#contactForm').serialize(),

});

In my file contact.php I try to validate the token (which doesn't work):

if (verifyFormToken('contactForm')) {
      bla bla bla...

Update

The functions mentioned above can be found at Serious Form Security.


Solution

  • I think you should change the header of your website to:

    session_start();