Dashboard sipadu mbip
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

csrf.php 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. if (!isset($_SESSION)) session_start();
  3. class CSRF {
  4. /**
  5. * Token name of the session / html form field
  6. * @var string
  7. */
  8. private $token_name;
  9. /**
  10. * When to timeout in seconds
  11. * @var number
  12. */
  13. private $timeout = 300;
  14. public function __construct($token_name) {
  15. $this->token_name = $token_name;
  16. }
  17. /**
  18. * Builds a new token and stores it in the session
  19. * @param string $token_name
  20. * @return token
  21. */
  22. public function get_token() {
  23. // create a token
  24. $token_value = hash('sha256', mt_rand(0, mt_getrandmax()) . microtime(true));
  25. // Stored token to the session
  26. $_SESSION['token_' . $this->token_name] = $this->token_name . '_' . $token_value;
  27. $_SESSION['token_time_' . $this->token_name] = time();
  28. // return new token to a HTML page
  29. return '<input type="hidden" name="token" value="' . $this->token_name . '_' . $token_value . '">';
  30. }
  31. /**
  32. * Check a token
  33. * @param string $token
  34. * @return bool
  35. */
  36. public function check_token($token) {
  37. // get a token from session
  38. $session_token = $this->get_token_from_session();
  39. $session_token_time = $this->get_token_time_from_session();
  40. // Lifetime of a token
  41. $token_time = time() - $session_token_time;
  42. // check a token
  43. if (($token_time < $this->timeout) && $session_token === $token) {
  44. return true;
  45. }
  46. // Unset token variables
  47. unset($_SESSION['token_' . $this->token_name]);
  48. unset($_SESSION['token_time_' . $this->token_name]);
  49. return false;
  50. }
  51. /**
  52. * Get token from a session
  53. * @return string
  54. */
  55. public function get_token_from_session() {
  56. return isset($_SESSION['token_' . $this->token_name]) ? $_SESSION['token_' . $this->token_name] : '';
  57. }
  58. /**
  59. * Get token creation time from a session
  60. * @return string
  61. */
  62. public function get_token_time_from_session() {
  63. return isset($_SESSION['token_time_' . $this->token_name]) ? $_SESSION['token_time_' . $this->token_name] : '';
  64. }
  65. }