PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/kohana/modules/userguide/guide/zh-cn/using.sessions.md

https://github.com/alfons56/Kohana
Markdown | 223 lines | 149 code | 74 blank | 0 comment | 0 complexity | 82160b5384927ec75f86f64a26326c8b MD5 | raw file
  1. # Using Sessions and Cookies
  2. Kohana provides a couple of classes that make it easy to work with both cookies and session. At a high level both sessions and cookies provide the same function. They allow the developer to store temporary or persistent information about a specific client for later retrieval.
  3. Cookies should be used for storing non-private data that is persistent for a long period of time. For example storing a user id or a language preference. Use the [Cookie] class for getting and setting cookies.
  4. [!!] Kohana uses "signed" cookies. Every cookie that is stored is combined with a secure hash to prevent modification of the cookie. This hash is generated using [Cookie::salt], which uses the [Cookie::$salt] property. You should [change this setting](using.configuration) when your application is live.
  5. Sessions should be used for storing temporary or private data. Very sensitive data should be stored using the [Session] class with the "database" or "native" adapters. When using the "cookie" adapter, the session should always be encrypted.
  6. [!!] For more information on best practices with session variables see [the seven deadly sins of sessions](http://lists.nyphp.org/pipermail/talk/2006-December/020358.html).
  7. # Storing, Retrieving, and Deleting Data
  8. [Cookie] and [Session] provide a very similar API for storing data. The main difference between them is that sessions are accessed using an object, and cookies are accessed using a static class.
  9. Accessing the session instance is done using the [Session::instance] method:
  10. // Get the session instance
  11. $session = Session::instance();
  12. When using sessions, you can also get all of the current session data using the [Session::as_array] method:
  13. // Get all of the session data as an array
  14. $data = $session->as_array();
  15. You can also use this to overload the `$_SESSION` global to get and set data in a way more similar to standard PHP:
  16. // Overload $_SESSION with the session data
  17. $_SESSION =& $session->as_array();
  18. // Set session data
  19. $_SESSION[$key] = $value;
  20. ## Storing Data {#setting}
  21. Storing session or cookie data is done using the `set` method:
  22. // Set session data
  23. $session->set($key, $value);
  24. // Set cookie data
  25. Cookie::set($key, $value);
  26. // Store a user id
  27. $session->set('user_id', 10);
  28. Cookie::set('user_id', 10);
  29. ## Retrieving Data {#getting}
  30. Getting session or cookie data is done using the `get` method:
  31. // Get session data
  32. $data = $session->get($key, $default_value);
  33. // Get cookie data
  34. $data = Cookie::get($key, $default_value);
  35. // Get the user id
  36. $user = $session->get('user_id');
  37. $user = Cookie::get('user_id');
  38. ## Deleting Data {#deleting}
  39. Deleting session or cookie data is done using the `delete` method:
  40. // Delete session data
  41. $session->delete($key);
  42. // Delete cookie data
  43. Cookie::delete($key);
  44. // Delete the user id
  45. $session->delete('user_id');
  46. Cookie::delete('user_id');
  47. # Configuration {#configuration}
  48. Both cookies and sessions have several configuration settings which affect how data is stored. Always check these settings before making your application live, as many of them will have a direct affect on the security of your application.
  49. ## Cookie Settings
  50. All of the cookie settings are changed using static properties. You can either change these settings in `bootstrap.php` or by using a [class extension](using.autoloading#class-extension).
  51. The most important setting is [Cookie::$salt], which is used for secure signing. This value should be changed and kept secret:
  52. Cookie::$salt = 'your secret is safe with me';
  53. [!!] Changing this value will render all cookies that have been set before invalid.
  54. By default, cookies are stored until the browser is closed. To use a specific lifetime, change the [Cookie::$expiration] setting:
  55. // Set cookies to expire after 1 week
  56. Cookie::$expiration = 604800;
  57. // Alternative to using raw integers, for better clarity
  58. Cookie::$expiration = Date::WEEK;
  59. The path that the cookie can be accessed from can be restricted using the [Cookie::$path] setting.
  60. // Allow cookies only when going to /public/*
  61. Cookie::$path = '/public/';
  62. The domain that the cookie can be accessed from can also be restricted, using the [Cookie::$domain] setting.
  63. // Allow cookies only on the domain www.example.com
  64. Cookie::$domain = 'www.example.com';
  65. If you want to make the cookie accessible on all subdomains, use a dot at the beginning of the domain.
  66. // Allow cookies to be accessed on example.com and *.example.com
  67. Cookie::$domain = '.example.com';
  68. To only allow the cookie to be accessed over a secure (HTTPS) connection, use the [Cookie::$secure] setting.
  69. // Allow cookies to be accessed only on a secure connection
  70. Cookie::$secure = TRUE;
  71. // Allow cookies to be accessed on any connection
  72. Cookie::$secure = FALSE;
  73. To prevent cookies from being accessed using Javascript, you can change the [Cookie::$httponly] setting.
  74. // Make cookies inaccessible to Javascript
  75. Cookie::$httponly = TRUE;
  76. ## Session Adapters {#adapters}
  77. When creating or accessing an instance of the [Session] class you can decide which session adapter you wish to use. The session adapters that are available to you are:
  78. Native
  79. : Stores session data in the default location for your web server. The storage location is defined by [session.save_path](http://php.net/manual/session.configuration.php#ini.session.save-path) in `php.ini` or defined by [ini_set](http://php.net/ini_set).
  80. Database
  81. : Stores session data in a database table using the [Session_Database] class. Requires the [Database] module to be enabled.
  82. Cookie
  83. : Stores session data in a cookie using the [Cookie] class. **Sessions will have a 4KB limit when using this adapter.**
  84. The default datapter can be set by changing the value of [Session::$default]. The default adapter is "native".
  85. [!!] As with cookies, a "lifetime" setting of "0" means that the session will expire when the browser is closed.
  86. ### Session Adapter Settings
  87. You can apply configuration settings to each of the session adapters by creating a session config file at `APPPATH/config/session.php`. The following sample configuration file defines all the settings for each adapater:
  88. return array(
  89. 'native' => array(
  90. 'name' => 'session_name',
  91. 'lifetime' => 43200,
  92. ),
  93. 'cookie' => array(
  94. 'name' => 'cookie_name',
  95. 'encrypted' => TRUE,
  96. 'lifetime' => 43200,
  97. ),
  98. 'database' => array(
  99. 'name' => 'cookie_name',
  100. 'encrypted' => TRUE,
  101. 'lifetime' => 43200,
  102. 'group' => 'default',
  103. 'table' => 'table_name',
  104. 'columns' => array(
  105. 'session_id' => 'session_id',
  106. 'last_active' => 'last_active',
  107. 'contents' => 'contents'
  108. ),
  109. 'gc' => 500,
  110. ),
  111. );
  112. #### Native Adapter {#adapter-native}
  113. Type | Setting | Description | Default
  114. ----------|-----------|---------------------------------------------------|-----------
  115. `string` | name | name of the session | `"session"`
  116. `integer` | lifetime | number of seconds the session should live for | `0`
  117. #### Cookie Adapter {#adapter-cookie}
  118. Type | Setting | Description | Default
  119. ----------|-----------|---------------------------------------------------|-----------
  120. `string` | name | name of the cookie used to store the session data | `"session"`
  121. `boolean` | encrypted | encrypt the session data using [Encrypt]? | `FALSE`
  122. `integer` | lifetime | number of seconds the session should live for | `0`
  123. #### Database Adapter {#adapter-database}
  124. Type | Setting | Description | Default
  125. ----------|-----------|---------------------------------------------------|-----------
  126. `string` | group | [Database::instance] group name | `"default"`
  127. `string` | table | table name to store sessions in | `"sessions"`
  128. `array` | columns | associative array of column aliases | `array`
  129. `integer` | gc | 1:x chance that garbage collection will be run | `500`
  130. `string` | name | name of the cookie used to store the session data | `"session"`
  131. `boolean` | encrypted | encrypt the session data using [Encrypt]? | `FALSE`
  132. `integer` | lifetime | number of seconds the session should live for | `0`
  133. ##### Table Schema
  134. You will need to create the session storage table in the database. This is the default schema:
  135. CREATE TABLE `sessions` (
  136. `session_id` VARCHAR(24) NOT NULL,
  137. `last_active` INT UNSIGNED NOT NULL,
  138. `contents` TEXT NOT NULL,
  139. PRIMARY KEY (`session_id`),
  140. INDEX (`last_active`)
  141. ) ENGINE = MYISAM;
  142. ##### Table Columns
  143. You can change the column names to match an existing database schema when connecting to a legacy session table. The default value is the same as the key value.
  144. session_id
  145. : the name of the "id" column
  146. last_active
  147. : UNIX timestamp of the last time the session was updated
  148. contents
  149. : session data stored as a serialized string, and optionally encrypted