cookie.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php namespace Laravel;
  2. class Cookie {
  3. /**
  4. * Determine if a cookie exists.
  5. *
  6. * @param string $name
  7. * @return bool
  8. */
  9. public static function has($name)
  10. {
  11. return ! is_null(static::get($name));
  12. }
  13. /**
  14. * Get the value of a cookie.
  15. *
  16. * @param string $name
  17. * @param mixed $default
  18. * @return string
  19. */
  20. public static function get($name, $default = null)
  21. {
  22. return Arr::get($_COOKIE, $name, $default);
  23. }
  24. /**
  25. * Set a "permanent" cookie. The cookie will last 5 years.
  26. *
  27. * @param string $name
  28. * @param string $value
  29. * @param string $path
  30. * @param string $domain
  31. * @param bool $secure
  32. * @param bool $http_only
  33. * @return bool
  34. */
  35. public static function forever($name, $value, $path = '/', $domain = null, $secure = false, $http_only = false)
  36. {
  37. return static::put($name, $value, 2628000, $path, $domain, $secure, $http_only);
  38. }
  39. /**
  40. * Set the value of a cookie.
  41. *
  42. * If a negative number of minutes is specified, the cookie will be deleted.
  43. *
  44. * Note: This method's signature is very similar to the PHP setcookie method.
  45. * However, you simply need to pass the number of minutes for which you
  46. * wish the cookie to be valid. No funky time calculation is required.
  47. *
  48. * @param string $name
  49. * @param string $value
  50. * @param int $minutes
  51. * @param string $path
  52. * @param string $domain
  53. * @param bool $secure
  54. * @param bool $http_only
  55. * @return bool
  56. */
  57. public static function put($name, $value, $minutes = 0, $path = '/', $domain = null, $secure = false, $http_only = false)
  58. {
  59. if (headers_sent()) return false;
  60. if ($minutes < 0) unset($_COOKIE[$name]);
  61. // Since PHP needs the cookie lifetime in seconds, we will calculate it here.
  62. // A "0" lifetime means the cookie expires when the browser closes.
  63. $time = ($minutes !== 0) ? time() + ($minutes * 60) : 0;
  64. return setcookie($name, $value, $time, $path, $domain, $secure, $http_only);
  65. }
  66. /**
  67. * Delete a cookie.
  68. *
  69. * @param string $name
  70. * @return bool
  71. */
  72. public static function forget($name)
  73. {
  74. return static::put($name, null, -60);
  75. }
  76. }