How to Use the session of the Framework in the php framework codeigniter

Source: Internet
Author: User
Tags php session codeigniter

There are two methods to use session:
1 is the original php session usage method. This is very simple. $ _ SESSION ['name'] = "name" is displayed as needed: echo $ _ SESSION ['name'];
2 is a method of the codeigniter framework:
The following describes how to use this complex method:
First, under \ ci \ application \ config. in the PHP file, find $ config ['encryption _ key'] = ''. You can enter any value in this file, but it cannot be blank. Generally, it is in English.
Then, auto under \ ci \ application \ config. find $ autoload ['libraries'] = array ('') in the PHP file. Enter $ autoload ['libraries'] = array ('session ') in the file '); or write $ this-> load-> library ('session ') in a proper place such as the corresponding file in the control folder (usually in the constructor '); this works.
Now the environment has been configured, and now the code is written:
Write where the session needs to be put:
$ This-> session-> set_userdata ('name', 'yang ');
In this way, the session has a value.
Display value:
Echo $ this-> session-> userdata ('name ');
If it is array, then:
$ Newdata = array (
'Username' => 'johndoe ',
'Email '=> 'johndoe @ some-site.com ',
'Logged _ in' => TRUE
);
$ This-> session-> set_userdata ($ newdata );
Below are some of the details of others that are reproduced in a bit nonsense:
Sessions starts to run after each page is loaded. Therefore, the session class must be initialized first.

1. You can initialize it in the Controller or automatically load it in the system. php setting) $ autoload ['libraries'] = array ('session ');

2. to initialize the session class in your controller constructor, you can use the $ this-> load-> library function: $ this-> load-> library ('session '); Once loaded, the session can be used as follows: $ this-> session.
Most session classes run in the background. Therefore, when a session is initialized, its session data is automatically read, created, and updated.

How does Sessions work?
It is important to know that the session class runs automatically once it is initialized. You can ignore the subsequent things. As you will see below, you can use the session to work normally, or even add your own session data. In all these processes, read, write, and update operations are automatically completed.

After the page is loaded, the session class checks whether the user's cookie contains valid session data. If the session data does not exist (or has expired), a new session is created and saved in the cookie. If the session data exists, its information will be updated and the cookie will be updated at the same time. The session_id value will be re-generated for each update.

By default, Session cookies are updated every five minutes, which reduces the workload on the processor. If you repeat the loading page, you will find that the time of the "last activity" Changes in five minutes, or the time when the cookie was last written. You can change this time by setting the $ config ['sess _ time_to_update '] Line in the application/config. php file.

A session is composed of an array containing the following information:
Unique User Session ID (this is a very robust random string calculated by the average amount of information. It is encrypted using MD5 and is regenerated every five minutes by default.
User IP Address
User browser information (take the first 50 characters)
The latest active timestamp.
The above data will be serialized and stored in the cookie in the following array format:

Copy codeThe Code is as follows: [array]
(
'Session _ id' => random hash,
'IP _ address' => 'string-user ip address ',
'User _ agent' => 'string-user agent data ',
'Last _ activity' => timestamp
)

1. Obtain Session data:
You can use the following function to obtain any information about the session array:
$ This-> session-> userdata ('item ');
Item is the index of the corresponding data in the array. For example, to obtain the session ID, you need to use the following code:
$ Session_id = $ this-> session-> userdata ('session _ id ');
NOTE: If your target data does not exist, this function returns FALSE (boolean ).

2. Add custom Session data:
Assume that a specific user has logged on to your website. After detection, you can add the user name and email to the session cookie, this information can be used as a global volume without accessing the database.
The following function transfers a new user group to the session array:
$ This-> session-> set_userdata ($ array );
$ Array is a combination of arrays to store your new data. For example:

Copy codeThe Code is as follows: $ newdata = array (
'Username' => 'johndoe ',
'Email '=> 'johndoe @ some-site.com ',
'Logged _ in' => TRUE
);
$ This-> session-> set_userdata ($ newdata );

If you use the following set_userdata () function, you can add only one user data at a time.
$ This-> session-> set_userdata ('some _ name', 'some _ value ');
Note: Cookies can only store 4 kb of data. When using Cookies, be careful to exceed its capacity. In particular, encryption will generate a data string that is longer than the original data, so be careful when you want to store the data size.

3. Delete Session data:Just as set_userdata () is used to add information to the session, the session key passed to the unset_userdata () function can be used to delete this information. For example, if you want to remove 'some _ name' from the session information ':
$ This-> session-> unset_userdata ('some _ name ');
You can also upload an associated array of the items to be deleted to this function.
$ Array_items = array ('username' => '', 'email '=> '');
$ This-> session-> unset_userdata ($ array_items );

4. Store Session data to the database:
When session data is available in the database, each time a valid session is found in the user cookie, a database query is executed to match it. If the session ID does not match, the session will be destroyed. Session IDs will never be updated. They will only be generated when a new Session is created.
To store sessions, you must first create a data table. This is the basic structure required by the session class (for MySQL ):

Copy codeThe Code is as follows: create table if not exists 'Ci _ session '(
Session_id varchar (40) DEFAULT '0' not null,
Ip_address varchar (16) DEFAULT '0' not null,
User_agent varchar (50) not null,
Last_activity int (10) unsigned DEFAULT 0 not null,
User_data text DEFAULT ''not null,
Primary key (session_id ));

Once enabled, the Session class will store session data in the database.
Make sure that you have specified the data table name in the configuration file: $ config ['sess _ table_name '] = 'Ci _ session ';
Note: by default, this table is called ci_sessions, but you can specify any name for it, as long as you update the application/config. php file to ensure that it contains your name. Once you create a data table, you can enable the database options in the config. php file as follows:
$ Config ['sess _ use_database '] = TRUE;
Note: The Session class has a built-in garbage collection mechanism for clearing expired sessions, so you do not need to write your own transactions to do this.

5. Destroy the Session
To clear the current session: $ this-> session-> sess_destroy ();
Session Parameters

6. You can find the following Session-related parameters in the application/config. php file:
Parameter default option description
Sess_cookie_name ci_session does not have the name you want to save the Session Cookie.
Sess_expiration 7200 the number of seconds in which no session lasts. The default value is 2 hours (7200 seconds ). If you set this value to: 0, you can get a permanent session.
Sess_expire_on_close false true/FALSE (boolean) This option determines whether to automatically expire the session when the browser window is closed.
Sess_encrypt_cookie false true/FALSE (boolean) Whether to encrypt session data.
Sess_use_database false true/FALSE (boolean) Whether to store session data in the database. Before enabling this option, you must create a database table.
Sess_table_name ci_sessions any valid SQL table name session database table name.
Sess_time_to_update 300 takes seconds to calculate how long the session class will generate a new session and session id.
Sess_match_ip false true/FALSE (boolean) Whether to read session data through the user's IP address. Note that some network operator ISPs dynamically changes the IP address. Therefore, if this option is set to FALSE, a permanent session may be obtained.
Sess_match_useragent TRUE/FALSE (boolean value) Whether to read session data according to the corresponding User Agent.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.