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.4 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.4
      • 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

Classes

  • CakeSession
  • DataSource
  • DboSource
  1: <?php
  2: /**
  3:  * Session class for CakePHP.
  4:  *
  5:  * CakePHP abstracts the handling of sessions.
  6:  * There are several convenient methods to access session information.
  7:  * This class is the implementation of those methods.
  8:  * They are mostly used by the Session Component.
  9:  *
 10:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 11:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 12:  *
 13:  * Licensed under The MIT License
 14:  * For full copyright and license information, please see the LICENSE.txt
 15:  * Redistributions of files must retain the above copyright notice.
 16:  *
 17:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 18:  * @link          http://cakephp.org CakePHP(tm) Project
 19:  * @package       Cake.Model.Datasource
 20:  * @since         CakePHP(tm) v .0.10.0.1222
 21:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 22:  */
 23: 
 24: App::uses('Hash', 'Utility');
 25: App::uses('Security', 'Utility');
 26: 
 27: /**
 28:  * Session class for CakePHP.
 29:  *
 30:  * CakePHP abstracts the handling of sessions. There are several convenient methods to access session information.
 31:  * This class is the implementation of those methods. They are mostly used by the Session Component.
 32:  *
 33:  * @package       Cake.Model.Datasource
 34:  */
 35: class CakeSession {
 36: 
 37: /**
 38:  * True if the Session is still valid
 39:  *
 40:  * @var boolean
 41:  */
 42:     public static $valid = false;
 43: 
 44: /**
 45:  * Error messages for this session
 46:  *
 47:  * @var array
 48:  */
 49:     public static $error = false;
 50: 
 51: /**
 52:  * User agent string
 53:  *
 54:  * @var string
 55:  */
 56:     protected static $_userAgent = '';
 57: 
 58: /**
 59:  * Path to where the session is active.
 60:  *
 61:  * @var string
 62:  */
 63:     public static $path = '/';
 64: 
 65: /**
 66:  * Error number of last occurred error
 67:  *
 68:  * @var integer
 69:  */
 70:     public static $lastError = null;
 71: 
 72: /**
 73:  * Start time for this session.
 74:  *
 75:  * @var integer
 76:  */
 77:     public static $time = false;
 78: 
 79: /**
 80:  * Cookie lifetime
 81:  *
 82:  * @var integer
 83:  */
 84:     public static $cookieLifeTime;
 85: 
 86: /**
 87:  * Time when this session becomes invalid.
 88:  *
 89:  * @var integer
 90:  */
 91:     public static $sessionTime = false;
 92: 
 93: /**
 94:  * Current Session id
 95:  *
 96:  * @var string
 97:  */
 98:     public static $id = null;
 99: 
100: /**
101:  * Hostname
102:  *
103:  * @var string
104:  */
105:     public static $host = null;
106: 
107: /**
108:  * Session timeout multiplier factor
109:  *
110:  * @var integer
111:  */
112:     public static $timeout = null;
113: 
114: /**
115:  * Number of requests that can occur during a session time without the session being renewed.
116:  * This feature is only used when config value `Session.autoRegenerate` is set to true.
117:  *
118:  * @var integer
119:  * @see CakeSession::_checkValid()
120:  */
121:     public static $requestCountdown = 10;
122: 
123: /**
124:  * Whether or not the init function in this class was already called
125:  *
126:  * @var boolean
127:  */
128:     protected static $_initialized = false;
129: 
130: /**
131:  * Pseudo constructor.
132:  *
133:  * @param string $base The base path for the Session
134:  * @return void
135:  */
136:     public static function init($base = null) {
137:         self::$time = time();
138: 
139:         if (env('HTTP_USER_AGENT')) {
140:             self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
141:         }
142: 
143:         self::_setPath($base);
144:         self::_setHost(env('HTTP_HOST'));
145: 
146:         if (!self::$_initialized) {
147:             register_shutdown_function('session_write_close');
148:         }
149: 
150:         self::$_initialized = true;
151:     }
152: 
153: /**
154:  * Setup the Path variable
155:  *
156:  * @param string $base base path
157:  * @return void
158:  */
159:     protected static function _setPath($base = null) {
160:         if (empty($base)) {
161:             self::$path = '/';
162:             return;
163:         }
164:         if (strpos($base, 'index.php') !== false) {
165:             $base = str_replace('index.php', '', $base);
166:         }
167:         if (strpos($base, '?') !== false) {
168:             $base = str_replace('?', '', $base);
169:         }
170:         self::$path = $base;
171:     }
172: 
173: /**
174:  * Set the host name
175:  *
176:  * @param string $host Hostname
177:  * @return void
178:  */
179:     protected static function _setHost($host) {
180:         self::$host = $host;
181:         if (strpos(self::$host, ':') !== false) {
182:             self::$host = substr(self::$host, 0, strpos(self::$host, ':'));
183:         }
184:     }
185: 
186: /**
187:  * Starts the Session.
188:  *
189:  * @return boolean True if session was started
190:  */
191:     public static function start() {
192:         if (self::started()) {
193:             return true;
194:         }
195: 
196:         $id = self::id();
197:         self::_startSession();
198: 
199:         if (!$id && self::started()) {
200:             self::_checkValid();
201:         }
202: 
203:         self::$error = false;
204:         self::$valid = true;
205:         return self::started();
206:     }
207: 
208: /**
209:  * Determine if Session has been started.
210:  *
211:  * @return boolean True if session has been started.
212:  */
213:     public static function started() {
214:         return isset($_SESSION) && session_id();
215:     }
216: 
217: /**
218:  * Returns true if given variable is set in session.
219:  *
220:  * @param string $name Variable name to check for
221:  * @return boolean True if variable is there
222:  */
223:     public static function check($name = null) {
224:         if (!self::start()) {
225:             return false;
226:         }
227:         if (empty($name)) {
228:             return false;
229:         }
230:         return Hash::get($_SESSION, $name) !== null;
231:     }
232: 
233: /**
234:  * Returns the session id.
235:  * Calling this method will not auto start the session. You might have to manually
236:  * assert a started session.
237:  *
238:  * Passing an id into it, you can also replace the session id if the session
239:  * has not already been started.
240:  * Note that depending on the session handler, not all characters are allowed
241:  * within the session id. For example, the file session handler only allows
242:  * characters in the range a-z A-Z 0-9 , (comma) and - (minus).
243:  *
244:  * @param string $id Id to replace the current session id
245:  * @return string Session id
246:  */
247:     public static function id($id = null) {
248:         if ($id) {
249:             self::$id = $id;
250:             session_id(self::$id);
251:         }
252:         if (self::started()) {
253:             return session_id();
254:         }
255:         return self::$id;
256:     }
257: 
258: /**
259:  * Removes a variable from session.
260:  *
261:  * @param string $name Session variable to remove
262:  * @return boolean Success
263:  */
264:     public static function delete($name) {
265:         if (self::check($name)) {
266:             self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
267:             return !self::check($name);
268:         }
269:         return false;
270:     }
271: 
272: /**
273:  * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself.
274:  *
275:  * @param array $old Set of old variables => values
276:  * @param array $new New set of variable => value
277:  * @return void
278:  */
279:     protected static function _overwrite(&$old, $new) {
280:         if (!empty($old)) {
281:             foreach ($old as $key => $var) {
282:                 if (!isset($new[$key])) {
283:                     unset($old[$key]);
284:                 }
285:             }
286:         }
287:         foreach ($new as $key => $var) {
288:             $old[$key] = $var;
289:         }
290:     }
291: 
292: /**
293:  * Return error description for given error number.
294:  *
295:  * @param integer $errorNumber Error to set
296:  * @return string Error as string
297:  */
298:     protected static function _error($errorNumber) {
299:         if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) {
300:             return false;
301:         }
302:         return self::$error[$errorNumber];
303:     }
304: 
305: /**
306:  * Returns last occurred error as a string, if any.
307:  *
308:  * @return mixed Error description as a string, or false.
309:  */
310:     public static function error() {
311:         if (self::$lastError) {
312:             return self::_error(self::$lastError);
313:         }
314:         return false;
315:     }
316: 
317: /**
318:  * Returns true if session is valid.
319:  *
320:  * @return boolean Success
321:  */
322:     public static function valid() {
323:         if (self::read('Config')) {
324:             if (self::_validAgentAndTime() && self::$error === false) {
325:                 self::$valid = true;
326:             } else {
327:                 self::$valid = false;
328:                 self::_setError(1, 'Session Highjacking Attempted !!!');
329:             }
330:         }
331:         return self::$valid;
332:     }
333: 
334: /**
335:  * Tests that the user agent is valid and that the session hasn't 'timed out'.
336:  * Since timeouts are implemented in CakeSession it checks the current self::$time
337:  * against the time the session is set to expire. The User agent is only checked
338:  * if Session.checkAgent == true.
339:  *
340:  * @return boolean
341:  */
342:     protected static function _validAgentAndTime() {
343:         $config = self::read('Config');
344:         $validAgent = (
345:             Configure::read('Session.checkAgent') === false ||
346:             self::$_userAgent == $config['userAgent']
347:         );
348:         return ($validAgent && self::$time <= $config['time']);
349:     }
350: 
351: /**
352:  * Get / Set the user agent
353:  *
354:  * @param string $userAgent Set the user agent
355:  * @return string Current user agent
356:  */
357:     public static function userAgent($userAgent = null) {
358:         if ($userAgent) {
359:             self::$_userAgent = $userAgent;
360:         }
361:         if (empty(self::$_userAgent)) {
362:             CakeSession::init(self::$path);
363:         }
364:         return self::$_userAgent;
365:     }
366: 
367: /**
368:  * Returns given session variable, or all of them, if no parameters given.
369:  *
370:  * @param string|array $name The name of the session variable (or a path as sent to Set.extract)
371:  * @return mixed The value of the session variable
372:  */
373:     public static function read($name = null) {
374:         if (!self::start()) {
375:             return false;
376:         }
377:         if ($name === null) {
378:             return self::_returnSessionVars();
379:         }
380:         if (empty($name)) {
381:             return false;
382:         }
383:         $result = Hash::get($_SESSION, $name);
384: 
385:         if (isset($result)) {
386:             return $result;
387:         }
388:         return null;
389:     }
390: 
391: /**
392:  * Returns all session variables.
393:  *
394:  * @return mixed Full $_SESSION array, or false on error.
395:  */
396:     protected static function _returnSessionVars() {
397:         if (!empty($_SESSION)) {
398:             return $_SESSION;
399:         }
400:         self::_setError(2, 'No Session vars set');
401:         return false;
402:     }
403: 
404: /**
405:  * Writes value to given session variable name.
406:  *
407:  * @param string|array $name Name of variable
408:  * @param string $value Value to write
409:  * @return boolean True if the write was successful, false if the write failed
410:  */
411:     public static function write($name, $value = null) {
412:         if (!self::start()) {
413:             return false;
414:         }
415:         if (empty($name)) {
416:             return false;
417:         }
418:         $write = $name;
419:         if (!is_array($name)) {
420:             $write = array($name => $value);
421:         }
422:         foreach ($write as $key => $val) {
423:             self::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
424:             if (Hash::get($_SESSION, $key) !== $val) {
425:                 return false;
426:             }
427:         }
428:         return true;
429:     }
430: 
431: /**
432:  * Helper method to destroy invalid sessions.
433:  *
434:  * @return void
435:  */
436:     public static function destroy() {
437:         if (!self::started()) {
438:             self::_startSession();
439:         }
440: 
441:         session_destroy();
442: 
443:         $_SESSION = null;
444:         self::$id = null;
445:     }
446: 
447: /**
448:  * Clears the session, the session id, and renews the session.
449:  *
450:  * @return void
451:  */
452:     public static function clear() {
453:         $_SESSION = null;
454:         self::$id = null;
455:         self::renew();
456:     }
457: 
458: /**
459:  * Helper method to initialize a session, based on CakePHP core settings.
460:  *
461:  * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
462:  *
463:  * @return void
464:  * @throws CakeSessionException Throws exceptions when ini_set() fails.
465:  */
466:     protected static function _configureSession() {
467:         $sessionConfig = Configure::read('Session');
468: 
469:         if (isset($sessionConfig['defaults'])) {
470:             $defaults = self::_defaultConfig($sessionConfig['defaults']);
471:             if ($defaults) {
472:                 $sessionConfig = Hash::merge($defaults, $sessionConfig);
473:             }
474:         }
475:         if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
476:             $sessionConfig['ini']['session.cookie_secure'] = 1;
477:         }
478:         if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
479:             $sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
480:         }
481:         if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
482:             $sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
483:         }
484:         if (!isset($sessionConfig['ini']['session.name'])) {
485:             $sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
486:         }
487:         if (!empty($sessionConfig['handler'])) {
488:             $sessionConfig['ini']['session.save_handler'] = 'user';
489:         }
490:         if (!isset($sessionConfig['ini']['session.gc_maxlifetime'])) {
491:             $sessionConfig['ini']['session.gc_maxlifetime'] = $sessionConfig['timeout'] * 60;
492:         }
493:         if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
494:             $sessionConfig['ini']['session.cookie_httponly'] = 1;
495:         }
496: 
497:         if (empty($_SESSION)) {
498:             if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
499:                 foreach ($sessionConfig['ini'] as $setting => $value) {
500:                     if (ini_set($setting, $value) === false) {
501:                         throw new CakeSessionException(__d('cake_dev', 'Unable to configure the session, setting %s failed.', $setting));
502:                     }
503:                 }
504:             }
505:         }
506:         if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) {
507:             call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
508:         }
509:         if (!empty($sessionConfig['handler']['engine'])) {
510:             $handler = self::_getHandler($sessionConfig['handler']['engine']);
511:             session_set_save_handler(
512:                 array($handler, 'open'),
513:                 array($handler, 'close'),
514:                 array($handler, 'read'),
515:                 array($handler, 'write'),
516:                 array($handler, 'destroy'),
517:                 array($handler, 'gc')
518:             );
519:         }
520:         Configure::write('Session', $sessionConfig);
521:         self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
522:     }
523: 
524: /**
525:  * Find the handler class and make sure it implements the correct interface.
526:  *
527:  * @param string $handler
528:  * @return void
529:  * @throws CakeSessionException
530:  */
531:     protected static function _getHandler($handler) {
532:         list($plugin, $class) = pluginSplit($handler, true);
533:         App::uses($class, $plugin . 'Model/Datasource/Session');
534:         if (!class_exists($class)) {
535:             throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
536:         }
537:         $handler = new $class();
538:         if ($handler instanceof CakeSessionHandlerInterface) {
539:             return $handler;
540:         }
541:         throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
542:     }
543: 
544: /**
545:  * Get one of the prebaked default session configurations.
546:  *
547:  * @param string $name
548:  * @return boolean|array
549:  */
550:     protected static function _defaultConfig($name) {
551:         $defaults = array(
552:             'php' => array(
553:                 'cookie' => 'CAKEPHP',
554:                 'timeout' => 240,
555:                 'ini' => array(
556:                     'session.use_trans_sid' => 0,
557:                     'session.cookie_path' => self::$path
558:                 )
559:             ),
560:             'cake' => array(
561:                 'cookie' => 'CAKEPHP',
562:                 'timeout' => 240,
563:                 'ini' => array(
564:                     'session.use_trans_sid' => 0,
565:                     'url_rewriter.tags' => '',
566:                     'session.serialize_handler' => 'php',
567:                     'session.use_cookies' => 1,
568:                     'session.cookie_path' => self::$path,
569:                     'session.save_path' => TMP . 'sessions',
570:                     'session.save_handler' => 'files'
571:                 )
572:             ),
573:             'cache' => array(
574:                 'cookie' => 'CAKEPHP',
575:                 'timeout' => 240,
576:                 'ini' => array(
577:                     'session.use_trans_sid' => 0,
578:                     'url_rewriter.tags' => '',
579:                     'session.use_cookies' => 1,
580:                     'session.cookie_path' => self::$path,
581:                     'session.save_handler' => 'user',
582:                 ),
583:                 'handler' => array(
584:                     'engine' => 'CacheSession',
585:                     'config' => 'default'
586:                 )
587:             ),
588:             'database' => array(
589:                 'cookie' => 'CAKEPHP',
590:                 'timeout' => 240,
591:                 'ini' => array(
592:                     'session.use_trans_sid' => 0,
593:                     'url_rewriter.tags' => '',
594:                     'session.use_cookies' => 1,
595:                     'session.cookie_path' => self::$path,
596:                     'session.save_handler' => 'user',
597:                     'session.serialize_handler' => 'php',
598:                 ),
599:                 'handler' => array(
600:                     'engine' => 'DatabaseSession',
601:                     'model' => 'Session'
602:                 )
603:             )
604:         );
605:         if (isset($defaults[$name])) {
606:             return $defaults[$name];
607:         }
608:         return false;
609:     }
610: 
611: /**
612:  * Helper method to start a session
613:  *
614:  * @return boolean Success
615:  */
616:     protected static function _startSession() {
617:         self::init();
618:         session_write_close();
619:         self::_configureSession();
620: 
621:         if (headers_sent()) {
622:             if (empty($_SESSION)) {
623:                 $_SESSION = array();
624:             }
625:         } else {
626:             // For IE<=8
627:             session_cache_limiter("must-revalidate");
628:             session_start();
629:         }
630:         return true;
631:     }
632: 
633: /**
634:  * Helper method to create a new session.
635:  *
636:  * @return void
637:  */
638:     protected static function _checkValid() {
639:         $config = self::read('Config');
640:         if ($config) {
641:             $sessionConfig = Configure::read('Session');
642: 
643:             if (self::valid()) {
644:                 self::write('Config.time', self::$sessionTime);
645:                 if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
646:                     $check = $config['countdown'];
647:                     $check -= 1;
648:                     self::write('Config.countdown', $check);
649: 
650:                     if ($check < 1) {
651:                         self::renew();
652:                         self::write('Config.countdown', self::$requestCountdown);
653:                     }
654:                 }
655:             } else {
656:                 $_SESSION = array();
657:                 self::destroy();
658:                 self::_setError(1, 'Session Highjacking Attempted !!!');
659:                 self::_startSession();
660:                 self::_writeConfig();
661:             }
662:         } else {
663:             self::_writeConfig();
664:         }
665:     }
666: 
667: /**
668:  * Writes configuration variables to the session
669:  *
670:  * @return void
671:  */
672:     protected static function _writeConfig() {
673:         self::write('Config.userAgent', self::$_userAgent);
674:         self::write('Config.time', self::$sessionTime);
675:         self::write('Config.countdown', self::$requestCountdown);
676:     }
677: 
678: /**
679:  * Restarts this session.
680:  *
681:  * @return void
682:  */
683:     public static function renew() {
684:         if (session_id()) {
685:             if (session_id() || isset($_COOKIE[session_name()])) {
686:                 setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
687:             }
688:             session_regenerate_id(true);
689:         }
690:     }
691: 
692: /**
693:  * Helper method to set an internal error message.
694:  *
695:  * @param integer $errorNumber Number of the error
696:  * @param string $errorMessage Description of the error
697:  * @return void
698:  */
699:     protected static function _setError($errorNumber, $errorMessage) {
700:         if (self::$error === false) {
701:             self::$error = array();
702:         }
703:         self::$error[$errorNumber] = $errorMessage;
704:         self::$lastError = $errorNumber;
705:     }
706: 
707: }
708: 
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