session_php techniques for how to use frames in PHP framework CodeIgniter

Source: Internet
Author: User
Tags autoload garbage collection md5 encryption session id php framework sessions true true codeigniter

There are two ways to use the session:
1 is PHP's original session use method, this is very simple, $_session[' name ']= ' name ', and then display in place where needed: Echo $_session[' name ';
2 is one way to codeigniter this framework:
Here's a detailed explanation of how to use this somewhat complicated approach:
First, find in the config.php file below \ci\application\config: $config [' encryption_key '] = '; it can be filled with whatever value you want, but not empty. English is generally ah, do not get into a dead alley.
It is then found in the auto.php file below \ci\application\config: $autoload [' libraries '] = array ('); Inside to fill in: $autoload [' libraries '] = Array ( ' Session ', or in the appropriate place, as in the corresponding file in the control folder (typically in the construction method): $this->load->library (' Session ');
Now that the environment is configured, it's time to write code:
write in the place where you want to put the session:
$this->session->set_userdata (' name ', ' Yang ');
So there's a value in the session.
Display values:
echo $this->session->userdata (' name ');
If this is an array, then:
$newdata = Array (
' username ' => ' johndoe ',
' Email ' => ' johndoe@some-site.com ',
' Logged_in ' => TRUE
);
$this->session->set_userdata ($newdata);
The following is reproduced in the details of others a little nonsense about the relevant knowledge:
Sessions will start running after each page is loaded, so the session class must be initialized first.

1, you can initialize in the controller, can also be loaded automatically in the system (Translator Note: in autoload.php set) $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 '); The session can be used in this way: $this->session.
Most of the session class runs in the background, so the session data is automatically read, created, and updated when you initialize it.

How does the Sessions work?
It is important to know that the session class is automatically run once it is initialized. You can completely disregard the things that follow. As you'll see below, you can work with sessions normally and even add your own session data, and in all of this, read, write, and update operations are done automatically.

When the page is loaded, the session class checks to see if a valid session data exists in the user's cookie. If the session data does not exist (or has expired), a new one is created and saved to the cookie. If the session data exists, his information is updated and the cookie is updated simultaneously. Each update regenerates the session_id value.

By default, the session Cookie is updated every 5 minutes, which reduces the load on the processor. If you repeat the loading page, you will notice that the "last activity" time is five minutes or more than five minutes away, which is the time the cookie was last written. This time can be changed by setting the $config [' sess_time_to_update '] line in the application/config/config.php file.

A session is made up of an array that includes the following information:
Unique user session ID (this is a very strong random string of average information statistics, using MD5 encryption, which is regenerated every five minutes by default).
User's IP Address
User browser information (take the first 50 characters)
The latest active timestamp.
The above data will be serialized into the cookie in the following array format:

Copy Code code as follows:

[Array]
(
' session_id ' => random hash,
' IP_Address ' => ' string-user IP address ',
' User_agent ' => ' string-user agent data ',
' Last_activity ' => timestamp
)

1. Get Session data:
You can get any information about the session array by using the following function:
$this->session->userdata (' item ');
Item is the index of the corresponding data in the array. For example, to get the session ID, you would use the following code:
$session _id = $this->session->userdata (' session_id ');
Note: If your target data does not exist, this function returns FALSE (Booleans Boolean).

2. Add Custom session data:
Suppose a specific user logs on to your site, and when he detects that you can add his username and email to the session cookie, the information can be used as a global amount without accessing the database.
With the following functions, you can pass a new user array to the session array:
$this->session->set_userdata ($array);
$array is a associative array to store your new data. For example:

Copy Code code 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 store only 4KB of data and be careful to exceed its capacity when used. Specifically, encryption produces data strings that are longer than the original data, so be sure to be careful about the size of the data you want to store.

3, delete session data: just as using Set_userdata () is used to add information to the session, and by passing the session key to the Unset_userdata () function can be used to delete this information. For example, you want to remove ' some_name ' from session information:
$this->session->unset_userdata (' some_name ');
You can also pass an associative array to the function to delete the item.
$array _items = Array (' username ' => ', ' email ' => ');
$this->session->unset_userdata ($array _items);

4, the session data into the database:
When session data is available in the database, a database query is executed to match it whenever a valid session is found from the user cookie. The session is destroyed if the session ID does not match. Session IDs are never updated, and they are only generated when a new conversation is created.
In order to store the session, you must first create a data table. This is the basic structure required for the session class (for MySQL):

Copy Code code as follows:

CREATE TABLE IF not EXISTS ' ci_sessions ' (
session_id varchar (+) DEFAULT ' 0 ' not NULL,
IP_Address varchar () DEFAULT ' 0 ' not NULL,
User_agent varchar (m) not NULL,
last_activity Int (a) unsigned DEFAULT 0 not NULL,
User_data text DEFAULT ' not NULL,
PRIMARY KEY (session_id));

Once enabled, the session class stores the sessions data in the database.
Also make sure that you have specified the data table name in the configuration file: $config [' sess_table_name '] = ' ci_sessions ';
Note: This table is called Ci_sessions by default, but you can give it an arbitrary name, as long as you update the application/config/config.php file to make sure it contains your name. Once you create the datasheet, you can enable the database option in the config.php file as follows:
$config [' sess_use_database '] = TRUE;
Note: The session class has built-in garbage collection that clears expired sessions, so you don't have to write your own business to do this.

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

6, you can find the following session-related parameters in the application/config/config.php file:
Parameter default option description
Sess_cookie_name ci_session No name you want to save the session cookie.
Sess_expiration 7200 The number of seconds without session duration. The default is 2 hours (7,200 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 the session expires automatically when the browser window closes.
Sess_encrypt_cookie FALSE True/false (Boolean) whether the session data is encrypted.
Sess_use_database FALSE True/false (Boolean) whether the session data is stored in the database. Before you turn on this option, you need to create a database table first.
Sess_table_name Ci_sessions The name of any valid SQL table name session database table.
Sess_time_to_update 300 time in seconds this option controls how long the session class will produce a new sessions and the duration ID.
Sess_match_ip FALSE True/false (Boolean) whether to read the session's data through the user's IP address. Note that some network operators ISPs dynamically change the IP, so setting this option to FALSE will make it possible to get a permanent session.
Sess_match_useragent TRUE True/false Boolean Boolean 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.