-
Notifications
You must be signed in to change notification settings - Fork 773
Expand file tree
/
Copy pathCsrf.php
More file actions
60 lines (55 loc) · 1.48 KB
/
Csrf.php
File metadata and controls
60 lines (55 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
/**
* Cross Site Request Forgery Class
*
*/
/**
* Instructions:
*
* At your form, before the submit button put:
* <input type="hidden" name="csrf_token" value="<?= Csrf::makeToken(); ?>" />
*
* This validation needed in the controller action method to validate CSRF token submitted with the form:
*
* if (!Csrf::isTokenValid()) {
* LoginModel::logout();
* Redirect::home();
* exit();
* }
*
* To get simpler code it might be better to put the logout, redirect, exit into an own (static) method.
*/
class Csrf
{
/**
* get CSRF token and generate a new one if expired
*
* @access public
* @static static method
* @return string
*/
public static function makeToken()
{
// token is valid for 1 day
$max_time = 60 * 60 * 24;
$stored_time = Session::get('csrf_token_time');
$csrf_token = Session::get('csrf_token');
if ($max_time + $stored_time <= time() || empty($csrf_token)) {
Session::set('csrf_token', md5(uniqid(rand(), true)));
Session::set('csrf_token_time', time());
}
return Session::get('csrf_token');
}
/**
* checks if CSRF token in session is same as in the form submitted
*
* @access public
* @static static method
* @return bool
*/
public static function isTokenValid()
{
$token = Request::post('csrf_token');
return $token === Session::get('csrf_token') && !empty($token);
}
}