CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.10 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.10
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper
  • None

Classes

  • AclComponent
  • AuthComponent
  • CookieComponent
  • EmailComponent
  • FlashComponent
  • PaginatorComponent
  • RequestHandlerComponent
  • SecurityComponent
  • SessionComponent
  1: <?php
  2: /**
  3:  * Cookie Component
  4:  *
  5:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  6:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  7:  *
  8:  * Licensed under The MIT License
  9:  * For full copyright and license information, please see the LICENSE.txt
 10:  * Redistributions of files must retain the above copyright notice.
 11:  *
 12:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 13:  * @link          https://cakephp.org CakePHP(tm) Project
 14:  * @package       Cake.Controller.Component
 15:  * @since         CakePHP(tm) v 1.2.0.4213
 16:  * @license       https://opensource.org/licenses/mit-license.php MIT License
 17:  */
 18: 
 19: App::uses('Component', 'Controller');
 20: App::uses('Security', 'Utility');
 21: App::uses('Hash', 'Utility');
 22: 
 23: /**
 24:  * Cookie Component.
 25:  *
 26:  * Cookie handling for the controller.
 27:  *
 28:  * @package       Cake.Controller.Component
 29:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/cookie.html
 30:  */
 31: class CookieComponent extends Component {
 32: 
 33: /**
 34:  * The name of the cookie.
 35:  *
 36:  * Overridden with the controller beforeFilter();
 37:  * $this->Cookie->name = 'CookieName';
 38:  *
 39:  * @var string
 40:  */
 41:     public $name = 'CakeCookie';
 42: 
 43: /**
 44:  * The time a cookie will remain valid.
 45:  *
 46:  * Can be either integer Unix timestamp or a date string.
 47:  *
 48:  * Overridden with the controller beforeFilter();
 49:  * $this->Cookie->time = '5 Days';
 50:  *
 51:  * @var mixed
 52:  */
 53:     public $time = null;
 54: 
 55: /**
 56:  * Cookie path.
 57:  *
 58:  * Overridden with the controller beforeFilter();
 59:  * $this->Cookie->path = '/';
 60:  *
 61:  * The path on the server in which the cookie will be available on.
 62:  * If public $cookiePath is set to '/foo/', the cookie will only be available
 63:  * within the /foo/ directory and all sub-directories such as /foo/bar/ of domain.
 64:  * The default value is the entire domain.
 65:  *
 66:  * @var string
 67:  */
 68:     public $path = '/';
 69: 
 70: /**
 71:  * Domain path.
 72:  *
 73:  * The domain that the cookie is available.
 74:  *
 75:  * Overridden with the controller beforeFilter();
 76:  * $this->Cookie->domain = '.example.com';
 77:  *
 78:  * To make the cookie available on all subdomains of example.com.
 79:  * Set $this->Cookie->domain = '.example.com'; in your controller beforeFilter
 80:  *
 81:  * @var string
 82:  */
 83:     public $domain = '';
 84: 
 85: /**
 86:  * Secure HTTPS only cookie.
 87:  *
 88:  * Overridden with the controller beforeFilter();
 89:  * $this->Cookie->secure = true;
 90:  *
 91:  * Indicates that the cookie should only be transmitted over a secure HTTPS connection.
 92:  * When set to true, the cookie will only be set if a secure connection exists.
 93:  *
 94:  * @var bool
 95:  */
 96:     public $secure = false;
 97: 
 98: /**
 99:  * Encryption key.
100:  *
101:  * Overridden with the controller beforeFilter();
102:  * $this->Cookie->key = 'SomeRandomString';
103:  *
104:  * @var string
105:  */
106:     public $key = null;
107: 
108: /**
109:  * HTTP only cookie
110:  *
111:  * Set to true to make HTTP only cookies. Cookies that are HTTP only
112:  * are not accessible in JavaScript.
113:  *
114:  * @var bool
115:  */
116:     public $httpOnly = false;
117: 
118: /**
119:  * Values stored in the cookie.
120:  *
121:  * Accessed in the controller using $this->Cookie->read('Name.key');
122:  *
123:  * @see CookieComponent::read();
124:  * @var string
125:  */
126:     protected $_values = array();
127: 
128: /**
129:  * Type of encryption to use.
130:  *
131:  * Currently two methods are available: cipher and rijndael
132:  * Defaults to Security::cipher(). Cipher is horribly insecure and only
133:  * the default because of backwards compatibility. In new applications you should
134:  * always change this to 'aes' or 'rijndael'.
135:  *
136:  * @var string
137:  */
138:     protected $_type = 'cipher';
139: 
140: /**
141:  * Used to reset cookie time if $expire is passed to CookieComponent::write()
142:  *
143:  * @var string
144:  */
145:     protected $_reset = null;
146: 
147: /**
148:  * Expire time of the cookie
149:  *
150:  * This is controlled by CookieComponent::time;
151:  *
152:  * @var string
153:  */
154:     protected $_expires = 0;
155: 
156: /**
157:  * A reference to the Controller's CakeResponse object
158:  *
159:  * @var CakeResponse
160:  */
161:     protected $_response = null;
162: 
163: /**
164:  * Constructor
165:  *
166:  * @param ComponentCollection $collection A ComponentCollection for this component
167:  * @param array $settings Array of settings.
168:  */
169:     public function __construct(ComponentCollection $collection, $settings = array()) {
170:         $this->key = Configure::read('Security.salt');
171:         parent::__construct($collection, $settings);
172:         if (isset($this->time)) {
173:             $this->_expire($this->time);
174:         }
175: 
176:         $controller = $collection->getController();
177:         if ($controller && isset($controller->response)) {
178:             $this->_response = $controller->response;
179:         } else {
180:             $this->_response = new CakeResponse();
181:         }
182:     }
183: 
184: /**
185:  * Start CookieComponent for use in the controller
186:  *
187:  * @param Controller $controller Controller instance.
188:  * @return void
189:  */
190:     public function startup(Controller $controller) {
191:         $this->_expire($this->time);
192: 
193:         $this->_values[$this->name] = array();
194:     }
195: 
196: /**
197:  * Write a value to the $_COOKIE[$key];
198:  *
199:  * Optional [Name.], required key, optional $value, optional $encrypt, optional $expires
200:  * $this->Cookie->write('[Name.]key, $value);
201:  *
202:  * By default all values are encrypted.
203:  * You must pass $encrypt false to store values in clear test
204:  *
205:  * You must use this method before any output is sent to the browser.
206:  * Failure to do so will result in header already sent errors.
207:  *
208:  * @param string|array $key Key for the value
209:  * @param mixed $value Value
210:  * @param bool $encrypt Set to true to encrypt value, false otherwise
211:  * @param int|string $expires Can be either the number of seconds until a cookie
212:  *   expires, or a strtotime compatible time offset.
213:  * @return void
214:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::write
215:  */
216:     public function write($key, $value = null, $encrypt = true, $expires = null) {
217:         if (empty($this->_values[$this->name])) {
218:             $this->read();
219:         }
220: 
221:         if ($encrypt === null) {
222:             $encrypt = true;
223:         }
224:         $this->_encrypted = $encrypt;
225:         $this->_expire($expires);
226: 
227:         if (!is_array($key)) {
228:             $key = array($key => $value);
229:         }
230: 
231:         foreach ($key as $name => $value) {
232:             if (strpos($name, '.') !== false) {
233:                 $this->_values[$this->name] = Hash::insert($this->_values[$this->name], $name, $value);
234:                 list($name) = explode('.', $name, 2);
235:                 $value = $this->_values[$this->name][$name];
236:             } else {
237:                 $this->_values[$this->name][$name] = $value;
238:             }
239:             $this->_write('[' . $name . ']', $value);
240:         }
241:         $this->_encrypted = true;
242:     }
243: 
244: /**
245:  * Read the value of the $_COOKIE[$key];
246:  *
247:  * Optional [Name.], required key
248:  * $this->Cookie->read(Name.key);
249:  *
250:  * @param string $key Key of the value to be obtained. If none specified, obtain map key => values
251:  * @return string|array|null Value for specified key
252:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::read
253:  */
254:     public function read($key = null) {
255:         if (empty($this->_values[$this->name]) && isset($_COOKIE[$this->name])) {
256:             $this->_values[$this->name] = $this->_decrypt($_COOKIE[$this->name]);
257:         }
258:         if (empty($this->_values[$this->name])) {
259:             $this->_values[$this->name] = array();
260:         }
261:         if ($key === null) {
262:             return $this->_values[$this->name];
263:         }
264:         return Hash::get($this->_values[$this->name], $key);
265:     }
266: 
267: /**
268:  * Returns true if given variable is set in cookie.
269:  *
270:  * @param string $key Variable name to check for
271:  * @return bool True if variable is there
272:  */
273:     public function check($key = null) {
274:         if (empty($key)) {
275:             return false;
276:         }
277:         return $this->read($key) !== null;
278:     }
279: 
280: /**
281:  * Delete a cookie value
282:  *
283:  * Optional [Name.], required key
284:  * $this->Cookie->delete('Name.key);
285:  *
286:  * You must use this method before any output is sent to the browser.
287:  * Failure to do so will result in header already sent errors.
288:  *
289:  * This method will delete both the top level and 2nd level cookies set.
290:  * For example assuming that $name = App, deleting `User` will delete
291:  * both `App[User]` and any other cookie values like `App[User][email]`
292:  * This is done to clean up cookie storage from before 2.4.3, where cookies
293:  * were stored inconsistently.
294:  *
295:  * @param string $key Key of the value to be deleted
296:  * @return void
297:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::delete
298:  */
299:     public function delete($key) {
300:         if (empty($this->_values[$this->name])) {
301:             $this->read();
302:         }
303:         if (strpos($key, '.') === false) {
304:             unset($this->_values[$this->name][$key]);
305:             $this->_delete('[' . $key . ']');
306:         } else {
307:             $this->_values[$this->name] = Hash::remove((array)$this->_values[$this->name], $key);
308:             list($key) = explode('.', $key, 2);
309:             if (isset($this->_values[$this->name][$key])) {
310:                 $value = $this->_values[$this->name][$key];
311:                 $this->_write('[' . $key . ']', $value);
312:             }
313:         }
314:     }
315: 
316: /**
317:  * Destroy current cookie
318:  *
319:  * You must use this method before any output is sent to the browser.
320:  * Failure to do so will result in header already sent errors.
321:  *
322:  * @return void
323:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::destroy
324:  */
325:     public function destroy() {
326:         if (isset($_COOKIE[$this->name])) {
327:             $this->_values[$this->name] = $this->_decrypt($_COOKIE[$this->name]);
328:         }
329: 
330:         foreach ($this->_values[$this->name] as $name => $value) {
331:             $this->delete($name);
332:         }
333:     }
334: 
335: /**
336:  * Will allow overriding default encryption method. Use this method
337:  * in ex: AppController::beforeFilter() before you have read or
338:  * written any cookies.
339:  *
340:  * @param string $type Encryption method
341:  * @return void
342:  */
343:     public function type($type = 'cipher') {
344:         $availableTypes = array(
345:             'cipher',
346:             'rijndael',
347:             'aes'
348:         );
349:         if (!in_array($type, $availableTypes)) {
350:             trigger_error(__d('cake_dev', 'You must use cipher, rijndael or aes for cookie encryption type'), E_USER_WARNING);
351:             $type = 'cipher';
352:         }
353:         $this->_type = $type;
354:     }
355: 
356: /**
357:  * Set the expire time for a session variable.
358:  *
359:  * Creates a new expire time for a session variable.
360:  * $expire can be either integer Unix timestamp or a date string.
361:  *
362:  * Used by write()
363:  * CookieComponent::write(string, string, boolean, 8400);
364:  * CookieComponent::write(string, string, boolean, '5 Days');
365:  *
366:  * @param int|string $expires Can be either Unix timestamp, or date string
367:  * @return int Unix timestamp
368:  */
369:     protected function _expire($expires = null) {
370:         if ($expires === null) {
371:             return $this->_expires;
372:         }
373:         $this->_reset = $this->_expires;
374:         if (!$expires) {
375:             return $this->_expires = 0;
376:         }
377:         $now = new DateTime();
378: 
379:         if (is_int($expires) || is_numeric($expires)) {
380:             return $this->_expires = $now->format('U') + (int)$expires;
381:         }
382:         $now->modify($expires);
383:         return $this->_expires = $now->format('U');
384:     }
385: 
386: /**
387:  * Set cookie
388:  *
389:  * @param string $name Name for cookie
390:  * @param string $value Value for cookie
391:  * @return void
392:  */
393:     protected function _write($name, $value) {
394:         $this->_response->cookie(array(
395:             'name' => $this->name . $name,
396:             'value' => $this->_encrypt($value),
397:             'expire' => $this->_expires,
398:             'path' => $this->path,
399:             'domain' => $this->domain,
400:             'secure' => $this->secure,
401:             'httpOnly' => $this->httpOnly
402:         ));
403: 
404:         if (!empty($this->_reset)) {
405:             $this->_expires = $this->_reset;
406:             $this->_reset = null;
407:         }
408:     }
409: 
410: /**
411:  * Sets a cookie expire time to remove cookie value
412:  *
413:  * @param string $name Name of cookie
414:  * @return void
415:  */
416:     protected function _delete($name) {
417:         $this->_response->cookie(array(
418:             'name' => $this->name . $name,
419:             'value' => '',
420:             'expire' => time() - 42000,
421:             'path' => $this->path,
422:             'domain' => $this->domain,
423:             'secure' => $this->secure,
424:             'httpOnly' => $this->httpOnly
425:         ));
426:     }
427: 
428: /**
429:  * Encrypts $value using public $type method in Security class
430:  *
431:  * @param string $value Value to encrypt
432:  * @return string Encoded values
433:  */
434:     protected function _encrypt($value) {
435:         if (is_array($value)) {
436:             $value = $this->_implode($value);
437:         }
438:         if (!$this->_encrypted) {
439:             return $value;
440:         }
441:         $prefix = "Q2FrZQ==.";
442:         if ($this->_type === 'rijndael') {
443:             $cipher = Security::rijndael($value, $this->key, 'encrypt');
444:         }
445:         if ($this->_type === 'cipher') {
446:             $cipher = Security::cipher($value, $this->key);
447:         }
448:         if ($this->_type === 'aes') {
449:             $cipher = Security::encrypt($value, $this->key);
450:         }
451:         return $prefix . base64_encode($cipher);
452:     }
453: 
454: /**
455:  * Decrypts $value using public $type method in Security class
456:  *
457:  * @param array $values Values to decrypt
458:  * @return array decrypted string
459:  */
460:     protected function _decrypt($values) {
461:         $decrypted = array();
462:         $type = $this->_type;
463: 
464:         foreach ((array)$values as $name => $value) {
465:             if (is_array($value)) {
466:                 foreach ($value as $key => $val) {
467:                     $decrypted[$name][$key] = $this->_decode($val);
468:                 }
469:             } else {
470:                 $decrypted[$name] = $this->_decode($value);
471:             }
472:         }
473:         return $decrypted;
474:     }
475: 
476: /**
477:  * Decodes and decrypts a single value.
478:  *
479:  * @param string $value The value to decode & decrypt.
480:  * @return string|array Decoded value.
481:  */
482:     protected function _decode($value) {
483:         $prefix = 'Q2FrZQ==.';
484:         $pos = strpos($value, $prefix);
485:         if ($pos === false) {
486:             return $this->_explode($value);
487:         }
488:         $value = base64_decode(substr($value, strlen($prefix)));
489:         if ($this->_type === 'rijndael') {
490:             $plain = Security::rijndael($value, $this->key, 'decrypt');
491:         }
492:         if ($this->_type === 'cipher') {
493:             $plain = Security::cipher($value, $this->key);
494:         }
495:         if ($this->_type === 'aes') {
496:             $plain = Security::decrypt($value, $this->key);
497:         }
498:         return $this->_explode($plain);
499:     }
500: 
501: /**
502:  * Implode method to keep keys are multidimensional arrays
503:  *
504:  * @param array $array Map of key and values
505:  * @return string A json encoded string.
506:  */
507:     protected function _implode(array $array) {
508:         return json_encode($array);
509:     }
510: 
511: /**
512:  * Explode method to return array from string set in CookieComponent::_implode()
513:  * Maintains reading backwards compatibility with 1.x CookieComponent::_implode().
514:  *
515:  * @param string $string A string containing JSON encoded data, or a bare string.
516:  * @return string|array Map of key and values
517:  */
518:     protected function _explode($string) {
519:         $first = substr($string, 0, 1);
520:         if ($first === '{' || $first === '[') {
521:             $ret = json_decode($string, true);
522:             return ($ret !== null) ? $ret : $string;
523:         }
524:         $array = array();
525:         foreach (explode(',', $string) as $pair) {
526:             $key = explode('|', $pair);
527:             if (!isset($key[1])) {
528:                 return $key[0];
529:             }
530:             $array[$key[0]] = $key[1];
531:         }
532:         return $array;
533:     }
534: }
535: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs