cookie.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php namespace Laravel;
  2. class Cookie {
  3. /**
  4. * The cookies for the current request.
  5. *
  6. * @var array
  7. */
  8. protected $cookies;
  9. /**
  10. * Create a new cookie manager instance.
  11. *
  12. * @param array $cookies
  13. * @return void
  14. */
  15. public function __construct(&$cookies)
  16. {
  17. $this->cookies =& $cookies;
  18. }
  19. /**
  20. * Determine if a cookie exists.
  21. *
  22. * @param string $name
  23. * @return bool
  24. */
  25. public function has($name)
  26. {
  27. return ! is_null($this->get($name));
  28. }
  29. /**
  30. * Get the value of a cookie.
  31. *
  32. * @param string $name
  33. * @param mixed $default
  34. * @return string
  35. */
  36. public function get($name, $default = null)
  37. {
  38. return Arr::get($_COOKIE, $name, $default);
  39. }
  40. /**
  41. * Set a "permanent" cookie. The cookie will last 5 years.
  42. *
  43. * @param string $name
  44. * @param string $value
  45. * @param string $path
  46. * @param string $domain
  47. * @param bool $secure
  48. * @param bool $http_only
  49. * @return bool
  50. */
  51. public function forever($name, $value, $path = '/', $domain = null, $secure = false, $http_only = false)
  52. {
  53. return $this->put($name, $value, 2628000, $path, $domain, $secure, $http_only);
  54. }
  55. /**
  56. * Set the value of a cookie.
  57. *
  58. * If a negative number of minutes is specified, the cookie will be deleted.
  59. *
  60. * Note: This method's signature is very similar to the PHP setcookie method.
  61. * However, you simply need to pass the number of minutes for which you
  62. * wish the cookie to be valid. No funky time calculation is required.
  63. *
  64. * @param string $name
  65. * @param string $value
  66. * @param int $minutes
  67. * @param string $path
  68. * @param string $domain
  69. * @param bool $secure
  70. * @param bool $http_only
  71. * @return bool
  72. */
  73. public function put($name, $value, $minutes = 0, $path = '/', $domain = null, $secure = false, $http_only = false)
  74. {
  75. if (headers_sent()) return false;
  76. if ($minutes < 0) unset($_COOKIE[$name]);
  77. $time = ($minutes != 0) ? time() + ($minutes * 60) : 0;
  78. return setcookie($name, $value, $time, $path, $domain, $secure, $http_only);
  79. }
  80. /**
  81. * Delete a cookie.
  82. *
  83. * @param string $name
  84. * @return bool
  85. */
  86. public function forget($name)
  87. {
  88. return $this->put($name, null, -60);
  89. }
  90. }