Cookie.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. class Cookie {
  3. public static function checksum($key, $val) {
  4. return md5(UOJConfig::$data['security']['cookie']['checksum_salt'][0] . $key . UOJConfig::$data['security']['cookie']['checksum_salt'][1] . $val . UOJConfig::$data['security']['cookie']['checksum_salt'][2]);
  5. }
  6. public static function get($key) {
  7. return isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
  8. }
  9. public static function set($key, $val, $expire = 0, $path = null, $config = array()) {
  10. $config = array_merge(array(
  11. 'secure' => false,
  12. 'httponly' => false
  13. ), $config);
  14. $_COOKIE[$key] = $val;
  15. return setcookie($key, $val, $expire, $path, UOJContext::cookieDomain(), $config['secure'], $config['httponly']);
  16. }
  17. public static function unsetVar($key, $path = null) {
  18. if (!isset($_COOKIE[$key])) {
  19. return true;
  20. }
  21. unset($_COOKIE[$key]);
  22. return setcookie($key, null, -1, $path, UOJContext::cookieDomain());
  23. }
  24. public static function safeCheck($key, $path = null) {
  25. if (!isset($_COOKIE[$key])) {
  26. return;
  27. }
  28. if (!isset($_COOKIE[$key . '_checksum']) || $_COOKIE[$key . '_checksum'] !== Cookie::checksum($key, $_COOKIE[$key])) {
  29. Cookie::safeUnset($key, $path);
  30. }
  31. }
  32. public static function safeUnset($key, $path = null) {
  33. Cookie::unsetVar($key, $path);
  34. Cookie::unsetVar($key . '_checksum', $path);
  35. }
  36. public static function safeGet($key, $path = null) {
  37. Cookie::safeCheck($key, $path);
  38. return Cookie::get($key);
  39. }
  40. public static function safeSet($key, $val, $expire = 0, $path = null, $config = array()) {
  41. Cookie::set($key, $val, $expire, $path, $config);
  42. Cookie::set($key . '_checksum', Cookie::checksum($key, $val), $expire, $path, $config);
  43. }
  44. }