Session.php 15.6 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8 9
namespace yii\web;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11 12 13
use yii\base\Component;
use yii\base\InvalidParamException;

Qiang Xue committed
14
/**
Qiang Xue committed
15
 * Session provides session-level data management and the related configurations.
Qiang Xue committed
16
 *
Qiang Xue committed
17 18
 * To start the session, call [[open()]]; To complete and send out session data, call [[close()]];
 * To destroy the session, call [[destroy()]].
Qiang Xue committed
19
 *
Qiang Xue committed
20
 * If [[autoStart]] is set true, the session will be started automatically
Qiang Xue committed
21 22
 * when the application component is initialized by the application.
 *
Qiang Xue committed
23
 * Session can be used like an array to set and get session data. For example,
Qiang Xue committed
24
 *
Qiang Xue committed
25 26 27 28 29 30 31 32
 * ~~~
 * $session = new Session;
 * $session->open();
 * $value1 = $session['name1'];  // get session variable 'name1'
 * $value2 = $session['name2'];  // get session variable 'name2'
 * foreach ($session as $name => $value) // traverse all session variables
 * $session['name3'] = $value3;  // set session variable 'name3'
 * ~~~
Qiang Xue committed
33
 *
Qiang Xue committed
34
 * Session can be extended to support customized session storage.
Qiang Xue committed
35 36 37 38
 * To do so, override [[useCustomStorage()]] so that it returns true, and
 * override these methods with the actual logic about using custom storage:
 * [[openSession()]], [[closeSession()]], [[readSession()]], [[writeSession()]],
 * [[destroySession()]] and [[gcSession()]].
Qiang Xue committed
39
 *
Qiang Xue committed
40
 * Session is a Web application component that can be accessed via
Qiang Xue committed
41
 * `Yii::$app->session`.
Qiang Xue committed
42
 *
Qiang Xue committed
43 44 45 46
 * @property boolean $useCustomStorage read-only. Whether to use custom storage.
 * @property boolean $isActive Whether the session has started.
 * @property string $id The current session ID.
 * @property string $name The current session name.
Qiang Xue committed
47 48 49
 * @property string $savePath The current session save path, defaults to '/tmp'.
 * @property array $cookieParams The session cookie parameters.
 * @property string $cookieMode How to use cookie to store session ID. Defaults to 'Allow'.
Qiang Xue committed
50
 * @property float $gcProbability The probability (percentage) that the gc (garbage collection) process is started on every session initialization.
Qiang Xue committed
51 52
 * @property boolean $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to false.
 * @property integer $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.
Qiang Xue committed
53
 * @property SessionIterator $iterator An iterator for traversing the session variables.
Qiang Xue committed
54 55 56 57
 * @property integer $count The number of session variables.
 * @property array $keys The list of session variable names.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
58
 * @since 2.0
Qiang Xue committed
59
 */
Qiang Xue committed
60
class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Countable
Qiang Xue committed
61 62
{
	/**
Qiang Xue committed
63
	 * @var boolean whether the session should be automatically started when the session component is initialized.
Qiang Xue committed
64
	 */
Qiang Xue committed
65
	public $autoStart = true;
Qiang Xue committed
66 67 68 69 70 71 72 73

	/**
	 * Initializes the application component.
	 * This method is required by IApplicationComponent and is invoked by application.
	 */
	public function init()
	{
		parent::init();
Qiang Xue committed
74
		if ($this->autoStart) {
Qiang Xue committed
75
			$this->open();
Qiang Xue committed
76 77
		}
		register_shutdown_function(array($this, 'close'));
Qiang Xue committed
78 79 80 81
	}

	/**
	 * Returns a value indicating whether to use custom session storage.
Qiang Xue committed
82 83 84
	 * This method should be overridden to return true by child classes that implement custom session storage.
	 * To implement custom session storage, override these methods: [[openSession()]], [[closeSession()]],
	 * [[readSession()]], [[writeSession()]], [[destroySession()]] and [[gcSession()]].
Qiang Xue committed
85 86 87 88 89 90 91 92
	 * @return boolean whether to use custom storage.
	 */
	public function getUseCustomStorage()
	{
		return false;
	}

	/**
Qiang Xue committed
93
	 * Starts the session.
Qiang Xue committed
94 95 96
	 */
	public function open()
	{
Qiang Xue committed
97 98 99 100 101 102 103
		// this is available in PHP 5.4.0+
		if (function_exists('session_status')) {
			if (session_status() == PHP_SESSION_ACTIVE) {
				return;
			}
		}

Qiang Xue committed
104
		if ($this->getUseCustomStorage()) {
Qiang Xue committed
105 106 107 108 109 110 111 112
			@session_set_save_handler(
				array($this, 'openSession'),
				array($this, 'closeSession'),
				array($this, 'readSession'),
				array($this, 'writeSession'),
				array($this, 'destroySession'),
				array($this, 'gcSession')
			);
Qiang Xue committed
113
		}
Qiang Xue committed
114 115

		@session_start();
Qiang Xue committed
116 117 118 119 120

		if (session_id() == '') {
			$error = error_get_last();
			$message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
			Yii::warning($message, __CLASS__);
Qiang Xue committed
121 122 123 124 125 126 127 128
		}
	}

	/**
	 * Ends the current session and store session data.
	 */
	public function close()
	{
Qiang Xue committed
129
		if (session_id() !== '') {
Qiang Xue committed
130
			@session_write_close();
Qiang Xue committed
131
		}
Qiang Xue committed
132 133 134 135 136 137 138
	}

	/**
	 * Frees all session variables and destroys all data registered to a session.
	 */
	public function destroy()
	{
Qiang Xue committed
139
		if (session_id() !== '') {
Qiang Xue committed
140 141 142 143 144 145 146 147
			@session_unset();
			@session_destroy();
		}
	}

	/**
	 * @return boolean whether the session has started
	 */
Qiang Xue committed
148
	public function getIsActive()
Qiang Xue committed
149
	{
Qiang Xue committed
150 151 152 153 154 155 156
		if (function_exists('session_status')) {
			// available in PHP 5.4.0+
			return session_status() == PHP_SESSION_ACTIVE;
		} else {
			// this is not very reliable
			return session_id() !== '';
		}
Qiang Xue committed
157 158 159 160 161
	}

	/**
	 * @return string the current session ID
	 */
Qiang Xue committed
162
	public function getId()
Qiang Xue committed
163 164 165 166 167 168 169
	{
		return session_id();
	}

	/**
	 * @param string $value the session ID for the current session
	 */
Qiang Xue committed
170
	public function setId($value)
Qiang Xue committed
171 172 173 174 175
	{
		session_id($value);
	}

	/**
Qiang Xue committed
176 177
	 * Updates the current session ID with a newly generated one .
	 * Please refer to [[http://php.net/session_regenerate_id]] for more details.
Qiang Xue committed
178 179
	 * @param boolean $deleteOldSession Whether to delete the old associated session file or not.
	 */
Qiang Xue committed
180
	public function regenerateID($deleteOldSession = false)
Qiang Xue committed
181 182 183 184 185 186 187
	{
		session_regenerate_id($deleteOldSession);
	}

	/**
	 * @return string the current session name
	 */
Qiang Xue committed
188
	public function getName()
Qiang Xue committed
189 190 191 192 193
	{
		return session_name();
	}

	/**
Qiang Xue committed
194 195
	 * @param string $value the session name for the current session, must be an alphanumeric string.
	 * It defaults to "PHPSESSID".
Qiang Xue committed
196
	 */
Qiang Xue committed
197
	public function setName($value)
Qiang Xue committed
198 199 200 201 202 203 204 205 206 207 208 209 210
	{
		session_name($value);
	}

	/**
	 * @return string the current session save path, defaults to '/tmp'.
	 */
	public function getSavePath()
	{
		return session_save_path();
	}

	/**
Qiang Xue committed
211 212
	 * @param string $value the current session save path. This can be either a directory name or a path alias.
	 * @throws InvalidParamException if the path is not a valid directory
Qiang Xue committed
213 214 215
	 */
	public function setSavePath($value)
	{
Qiang Xue committed
216 217 218
		$path = Yii::getAlias($value);
		if ($path !== false && is_dir($path)) {
			session_save_path($path);
Qiang Xue committed
219
		} else {
Qiang Xue committed
220
			throw new InvalidParamException("Session save path is not a valid directory: $value");
Qiang Xue committed
221
		}
Qiang Xue committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
	}

	/**
	 * @return array the session cookie parameters.
	 * @see http://us2.php.net/manual/en/function.session-get-cookie-params.php
	 */
	public function getCookieParams()
	{
		return session_get_cookie_params();
	}

	/**
	 * Sets the session cookie parameters.
	 * The effect of this method only lasts for the duration of the script.
	 * Call this method before the session starts.
Qiang Xue committed
237 238
	 * @param array $value cookie parameters, valid keys include: lifetime, path, domain, secure and httponly.
	 * @throws InvalidParamException if the parameters are incomplete.
Qiang Xue committed
239 240 241 242
	 * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
	 */
	public function setCookieParams($value)
	{
Qiang Xue committed
243
		$data = session_get_cookie_params();
Qiang Xue committed
244 245
		extract($data);
		extract($value);
Qiang Xue committed
246
		if (isset($lifetime, $path, $domain, $secure, $httponly)) {
Qiang Xue committed
247 248
			session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly);
		} else {
Qiang Xue committed
249
			throw new InvalidParamException('Please make sure these parameters are provided: lifetime, path, domain, secure and httponly.');
Qiang Xue committed
250
		}
Qiang Xue committed
251 252 253
	}

	/**
Qiang Xue committed
254 255 256
	 * Returns the value indicating whether cookies should be used to store session IDs.
	 * @return boolean|null the value indicating whether cookies should be used to store session IDs.
	 * @see setUseCookies()
Qiang Xue committed
257
	 */
Qiang Xue committed
258
	public function getUseCookies()
Qiang Xue committed
259
	{
Qiang Xue committed
260
		if (ini_get('session.use_cookies') === '0') {
Qiang Xue committed
261 262 263
			return false;
		} elseif (ini_get('session.use_only_cookies') === '1') {
			return true;
Qiang Xue committed
264
		} else {
Qiang Xue committed
265
			return null;
Qiang Xue committed
266
		}
Qiang Xue committed
267 268 269
	}

	/**
Qiang Xue committed
270 271 272 273 274 275 276 277
	 * Sets the value indicating whether cookies should be used to store session IDs.
	 * Three states are possible:
	 *
	 * - true: cookies and only cookies will be used to store session IDs.
	 * - false: cookies will not be used to store session IDs.
	 * - null: if possible, cookies will be used to store session IDs; if not, other mechanisms will be used (e.g. GET parameter)
	 *
	 * @param boolean|null $value the value indicating whether cookies should be used to store session IDs.
Qiang Xue committed
278
	 */
Qiang Xue committed
279
	public function setUseCookies($value)
Qiang Xue committed
280
	{
Qiang Xue committed
281
		if ($value === false) {
Qiang Xue committed
282 283
			ini_set('session.use_cookies', '0');
			ini_set('session.use_only_cookies', '0');
Qiang Xue committed
284 285 286
		} elseif ($value === true) {
			ini_set('session.use_cookies', '1');
			ini_set('session.use_only_cookies', '1');
Qiang Xue committed
287
		} else {
Qiang Xue committed
288 289
			ini_set('session.use_cookies', '1');
			ini_set('session.use_only_cookies', '0');
Qiang Xue committed
290 291 292 293
		}
	}

	/**
Qiang Xue committed
294
	 * @return float the probability (percentage) that the GC (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
Qiang Xue committed
295 296 297
	 */
	public function getGCProbability()
	{
Qiang Xue committed
298
		return (float)(ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
Qiang Xue committed
299 300 301
	}

	/**
Qiang Xue committed
302 303
	 * @param float $value the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
	 * @throws InvalidParamException if the value is not between 0 and 100.
Qiang Xue committed
304 305 306
	 */
	public function setGCProbability($value)
	{
Qiang Xue committed
307
		if ($value >= 0 && $value <= 100) {
Qiang Xue committed
308 309 310
			// percent * 21474837 / 2147483647 ≈ percent * 0.01
			ini_set('session.gc_probability', floor($value * 21474836.47));
			ini_set('session.gc_divisor', 2147483647);
Qiang Xue committed
311
		} else {
Qiang Xue committed
312
			throw new InvalidParamException('GCProbability must be a value between 0 and 100.');
Qiang Xue committed
313
		}
Qiang Xue committed
314 315 316 317 318 319 320
	}

	/**
	 * @return boolean whether transparent sid support is enabled or not, defaults to false.
	 */
	public function getUseTransparentSessionID()
	{
Qiang Xue committed
321
		return ini_get('session.use_trans_sid') == 1;
Qiang Xue committed
322 323 324 325 326 327 328
	}

	/**
	 * @param boolean $value whether transparent sid support is enabled or not.
	 */
	public function setUseTransparentSessionID($value)
	{
Qiang Xue committed
329
		ini_set('session.use_trans_sid', $value ? '1' : '0');
Qiang Xue committed
330 331 332
	}

	/**
Qiang Xue committed
333 334
	 * @return integer the number of seconds after which data will be seen as 'garbage' and cleaned up.
	 * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
Qiang Xue committed
335 336 337 338 339 340 341 342 343 344 345
	 */
	public function getTimeout()
	{
		return (int)ini_get('session.gc_maxlifetime');
	}

	/**
	 * @param integer $value the number of seconds after which data will be seen as 'garbage' and cleaned up
	 */
	public function setTimeout($value)
	{
Qiang Xue committed
346
		ini_set('session.gc_maxlifetime', $value);
Qiang Xue committed
347 348 349 350
	}

	/**
	 * Session open handler.
Qiang Xue committed
351
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
352 353 354 355 356
	 * Do not call this method directly.
	 * @param string $savePath session save path
	 * @param string $sessionName session name
	 * @return boolean whether session is opened successfully
	 */
Qiang Xue committed
357
	public function openSession($savePath, $sessionName)
Qiang Xue committed
358 359 360 361 362 363
	{
		return true;
	}

	/**
	 * Session close handler.
Qiang Xue committed
364
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
365 366 367 368 369 370 371 372 373 374
	 * Do not call this method directly.
	 * @return boolean whether session is closed successfully
	 */
	public function closeSession()
	{
		return true;
	}

	/**
	 * Session read handler.
Qiang Xue committed
375
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
376 377 378 379 380 381 382 383 384 385 386
	 * Do not call this method directly.
	 * @param string $id session ID
	 * @return string the session data
	 */
	public function readSession($id)
	{
		return '';
	}

	/**
	 * Session write handler.
Qiang Xue committed
387
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
388 389 390 391 392
	 * Do not call this method directly.
	 * @param string $id session ID
	 * @param string $data session data
	 * @return boolean whether session write is successful
	 */
Qiang Xue committed
393
	public function writeSession($id, $data)
Qiang Xue committed
394 395 396 397 398 399
	{
		return true;
	}

	/**
	 * Session destroy handler.
Qiang Xue committed
400
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
401 402 403 404 405 406 407 408 409 410 411
	 * Do not call this method directly.
	 * @param string $id session ID
	 * @return boolean whether session is destroyed successfully
	 */
	public function destroySession($id)
	{
		return true;
	}

	/**
	 * Session GC (garbage collection) handler.
Qiang Xue committed
412
	 * This method should be overridden if [[useCustomStorage()]] returns true.
Qiang Xue committed
413 414 415 416 417 418 419 420 421 422 423 424
	 * Do not call this method directly.
	 * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
	 * @return boolean whether session is GCed successfully
	 */
	public function gcSession($maxLifetime)
	{
		return true;
	}

	/**
	 * Returns an iterator for traversing the session variables.
	 * This method is required by the interface IteratorAggregate.
Qiang Xue committed
425
	 * @return SessionIterator an iterator for traversing the session variables.
Qiang Xue committed
426 427 428
	 */
	public function getIterator()
	{
Qiang Xue committed
429
		return new SessionIterator;
Qiang Xue committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
	}

	/**
	 * Returns the number of items in the session.
	 * @return integer the number of session variables
	 */
	public function getCount()
	{
		return count($_SESSION);
	}

	/**
	 * Returns the number of items in the session.
	 * This method is required by Countable interface.
	 * @return integer number of items in the session.
	 */
	public function count()
	{
		return $this->getCount();
	}

	/**
	 * Returns the session variable value with the session variable name.
Qiang Xue committed
453 454
	 * If the session variable does not exist, the `$defaultValue` will be returned.
	 * @param string $key the session variable name
Qiang Xue committed
455 456 457
	 * @param mixed $defaultValue the default value to be returned when the session variable does not exist.
	 * @return mixed the session variable value, or $defaultValue if the session variable does not exist.
	 */
Qiang Xue committed
458
	public function get($key, $defaultValue = null)
Qiang Xue committed
459 460 461 462 463 464 465 466 467 468
	{
		return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
	}

	/**
	 * Adds a session variable.
	 * Note, if the specified name already exists, the old value will be removed first.
	 * @param mixed $key session variable name
	 * @param mixed $value session variable value
	 */
Qiang Xue committed
469
	public function add($key, $value)
Qiang Xue committed
470
	{
Qiang Xue committed
471
		$_SESSION[$key] = $value;
Qiang Xue committed
472 473 474 475 476 477 478 479 480
	}

	/**
	 * Removes a session variable.
	 * @param mixed $key the name of the session variable to be removed
	 * @return mixed the removed value, null if no such session variable.
	 */
	public function remove($key)
	{
Qiang Xue committed
481 482
		if (isset($_SESSION[$key])) {
			$value = $_SESSION[$key];
Qiang Xue committed
483 484
			unset($_SESSION[$key]);
			return $value;
Qiang Xue committed
485
		} else {
Qiang Xue committed
486
			return null;
Qiang Xue committed
487
		}
Qiang Xue committed
488 489 490 491 492 493 494
	}

	/**
	 * Removes all session variables
	 */
	public function clear()
	{
Qiang Xue committed
495
		foreach (array_keys($_SESSION) as $key) {
Qiang Xue committed
496
			unset($_SESSION[$key]);
Qiang Xue committed
497
		}
Qiang Xue committed
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
	}

	/**
	 * @param mixed $key session variable name
	 * @return boolean whether there is the named session variable
	 */
	public function contains($key)
	{
		return isset($_SESSION[$key]);
	}

	/**
	 * @return array the list of all session variables in array
	 */
	public function toArray()
	{
		return $_SESSION;
	}

	/**
	 * This method is required by the interface ArrayAccess.
	 * @param mixed $offset the offset to check on
	 * @return boolean
	 */
	public function offsetExists($offset)
	{
		return isset($_SESSION[$offset]);
	}

	/**
	 * This method is required by the interface ArrayAccess.
	 * @param integer $offset the offset to retrieve element.
	 * @return mixed the element at the offset, null if no element is found at the offset
	 */
	public function offsetGet($offset)
	{
		return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
	}

	/**
	 * This method is required by the interface ArrayAccess.
	 * @param integer $offset the offset to set element
	 * @param mixed $item the element value
	 */
Qiang Xue committed
542
	public function offsetSet($offset, $item)
Qiang Xue committed
543
	{
Qiang Xue committed
544
		$_SESSION[$offset] = $item;
Qiang Xue committed
545 546 547 548 549 550 551 552 553 554 555
	}

	/**
	 * This method is required by the interface ArrayAccess.
	 * @param mixed $offset the offset to unset element
	 */
	public function offsetUnset($offset)
	{
		unset($_SESSION[$offset]);
	}
}