Version: current

     1 <?php
     2 /**
     3  * A set of static methods for manipulating cookies.
     4  * @package sapphire
     5  * @subpackage misc
     6  */
     7 class Cookie {
     8     static $report_errors = true;
     9
    10     /**
    11      * Set a cookie variable
    12      *
    13      * @param string $name The variable name
    14      * @param string $value The variable value.  May be an array or object if you wish.
    15      * @param int $expiryDays The expiry time, in days.  Defaults to 90.
    16      * @param string $path See http://php.net/set_session
    17      * @param string $domain See http://php.net/set_session
    18      * @param boolean $secure See http://php.net/set_session
    19      * @param boolean $httpOnly See http://php.net/set_session (PHP 5.2+ only)
    20      */
    21     static function set($name, $value, $expiryDays = 90, $path = null, $domain = null, $secure = false, $httpOnly = false) {
    22         if(!headers_sent($file, $line)) {
    23             $expiry = $expiryDays > 0 ? time()+(86400*$expiryDays) : 0;
    24             $path = ($path) ? $path : Director::baseURL();
    25
    26             // Versions of PHP prior to 5.2 do not support the $httpOnly value
    27             if(version_compare(phpversion(), 5.2, '<')) {
    28                 setcookie($name, $value, $expiry, $path, $domain, $secure);
    29             } else {
    30                 setcookie($name, $value, $expiry, $path, $domain, $secure, $httpOnly);
    31             }
    32         } else {
    33             if(self::$report_errors) user_error("Cookie '$name' can't be set. The site started outputting was content at line $line in $file", E_USER_WARNING);
    34         }
    35     }
    36
    37     /**
    38      * Get a cookie variable
    39      */
    40     static function get($name) {
    41         return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null;
    42     }
    43
    44     static function forceExpiry( $name ) {
    45         if(!headers_sent($file, $line)) {
    46             setcookie( $name, null, time() - 86400 );
    47         }
    48     }
    49
    50     static function set_report_errors($reportErrors) {
    51         self::$report_errors = $reportErrors;
    52     }
    53     static function report_errors() {
    54         return self::$report_errors;
    55     }
    56 }
    57
    58 ?>
    59

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -