PageRenderTime 42ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/core/storage/Cookie.php

https://github.com/spaghettiphp/spaghettiphp
PHP | 95 lines | 74 code | 21 blank | 0 comment | 7 complexity | 347ef91d94bc19f43b4025ed3b63dc9a MD5 | raw file
  1. <?php
  2. class Cookie {
  3. public $expires;
  4. public $path = '/';
  5. public $domain = '';
  6. public $secure = false;
  7. public $key;
  8. public $name = 'SpaghettiCookie';
  9. public static $instance;
  10. public function __construct() {
  11. $this->key = Config::read('Security.salt');
  12. }
  13. public static function instance() {
  14. if(!isset(self::$instance)) {
  15. $c = __CLASS__;
  16. self::$instance = new $c;
  17. }
  18. return self::$instance;
  19. }
  20. public static function set($key, $value) {
  21. $self = self::instance();
  22. if(isset($self->$key)) {
  23. $self->$key = $value;
  24. return true;
  25. }
  26. return false;
  27. }
  28. public static function get($key) {
  29. $self = self::instance();
  30. if(isset($self->$key)) {
  31. return $self->$key;
  32. }
  33. }
  34. public static function delete($name) {
  35. $self = self::instance();
  36. $path = Mapper::normalize(Mapper::base() . $self->path);
  37. return setcookie($self->name . '[' . $name . ']', '', time() - 42000, $path, $self->domain, $self->secure);
  38. }
  39. public static function read($name) {
  40. $self = self::instance();
  41. if(array_key_exists($self->name, $_COOKIE)) {
  42. return self::decrypt($_COOKIE[$self->name][$name]);
  43. }
  44. }
  45. public static function write($name, $value, $expires = null) {
  46. $self = self::instance();
  47. $expires = $self->expire($expires);
  48. $path = Mapper::normalize(Mapper::base() . $self->path);
  49. return setcookie($self->name . '[' . $name . ']', self::encrypt($value), $expires, $path, $self->domain, $self->secure, true);
  50. }
  51. public static function encrypt($value) {
  52. $self = self::instance();
  53. $encripted = base64_encode(Security::cipher($value, $self->key));
  54. return 'U3BhZ2hldHRp.' . $encripted;
  55. }
  56. public static function decrypt($value) {
  57. $self = self::instance();
  58. $prefix = strpos($value, 'U3BhZ2hldHRp.');
  59. if($prefix !== false) {
  60. $encrypted = base64_decode(substr($value, $prefix + 13));
  61. return Security::cipher($encrypted, $self->key);
  62. }
  63. return false;
  64. }
  65. public function expire($expires) {
  66. $now = time();
  67. if(is_numeric($expires)) {
  68. return $this->expires = $now + $expires;
  69. }
  70. else {
  71. return $this->expires = strtotime($expires, $now);
  72. }
  73. }
  74. }