2013-08-24 23:53:52 +02:00
|
|
|
<?php
|
|
|
|
// Generates a token against CSRF
|
2013-08-26 09:52:04 +02:00
|
|
|
// ==============================
|
2013-08-30 22:33:06 +02:00
|
|
|
function generate_token($name = '') {
|
2013-08-26 09:52:04 +02:00
|
|
|
if(session_id() == '')
|
|
|
|
session_start();
|
|
|
|
|
2013-08-24 23:53:52 +02:00
|
|
|
$token = uniqid(rand(), true);
|
2013-08-26 09:52:04 +02:00
|
|
|
|
2013-08-24 23:53:52 +02:00
|
|
|
$_SESSION[$name.'_token'] = $token;
|
|
|
|
$_SESSION[$name.'_token_time'] = time();
|
2013-08-26 09:52:04 +02:00
|
|
|
|
2013-08-24 23:53:52 +02:00
|
|
|
return $token;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checks that the anti-CSRF token is correct
|
2013-08-26 09:52:04 +02:00
|
|
|
// ==========================================
|
2013-08-30 22:33:06 +02:00
|
|
|
function check_token($time, $name = '') {
|
2013-08-26 09:52:04 +02:00
|
|
|
if(session_id() == '')
|
|
|
|
session_start();
|
|
|
|
|
2013-09-25 22:09:25 +02:00
|
|
|
if(isset($_SESSION[$name.'_token']) && isset($_SESSION[$name.'_token_time']) && (isset($_POST['token']) || isset($_GET['token']))) {
|
|
|
|
if(!empty($_POST['token']))
|
|
|
|
$token = $_POST['token'];
|
|
|
|
else
|
|
|
|
$token = $_GET['token'];
|
|
|
|
|
|
|
|
if($_SESSION[$name.'_token'] == $token) {
|
2013-08-26 09:52:04 +02:00
|
|
|
if($_SESSION[$name.'_token_time'] >= (time() - (int) $time))
|
2013-08-24 23:53:52 +02:00
|
|
|
return true;
|
2013-08-26 09:52:04 +02:00
|
|
|
}
|
|
|
|
}
|
2013-08-24 23:53:52 +02:00
|
|
|
return false;
|
|
|
|
}
|