Home >Backend Development >PHP Tutorial >Parsing the session_PHP tutorial on how to use the framework in the php framework codeigniter

Parsing the session_PHP tutorial on how to use the framework in the php framework codeigniter

WBOY
WBOYOriginal
2016-07-21 15:03:53844browse

There are two ways to use session:
1 is the original session usage method of PHP. This is very simple, $_SESSION['name']="name", Then display it where needed: echo $_SESSION['name'];
2 is a method of the codeigniter framework:
The following will explain in detail how to use this somewhat complicated method:
First, find in the config.php file under ciapplicationconfig: $config['encryption_key'] = ''; You can fill in any value in this, but it cannot be empty. It’s usually in English, so don’t be too pretentious.
Then find in the auto.php file under ciapplicationconfig: $autoload['libraries'] = array(''); fill in: $autoload['libraries'] = array('session'); or in In an appropriate place, such as the corresponding file in the control folder (usually in the construction method), write: $this->load->library('session'); This will also work.
Now that the environment is configured, it’s time to write the code:
Write where you need to put the session:
$this->session->set_userdata('name' ,'yang');
In this way, there will be value in the session.
Display value: Echo $ this- & gt; session-& gt; userdata ('name');
If it is array, then:
$ newdata = array (
'username' = > 'johndoe',
'email' => 'johndoe@some-site.com',
'logged_in' => TRUE
);
$this->session- >set_userdata($newdata);
The following is detailed and somewhat nonsense knowledge reproduced by others:
Sessions will start running after each page is loaded, so the session class must be initialized first.

1. You can initialize it in the controller or automatically load it in the system (Translator's Note: Set in autoload.php) $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 Once loaded, session can be used like this: $this->session.

Most of the session class will run in the background, so when the session is initialized, its session data will be automatically read, created and updated.

How do Sessions work?
A very important thing to know is that once the session class is initialized, it will run automatically. You can completely ignore the rest. As you will see below, you can use the session to work normally, and you can even add your own session data, and in the process, the reading, writing and updating operations are completed automatically.

When the page is loaded, the session class will check whether there is valid session data in the user's cookie. If the session data does not exist (or has expired), a new session will be created and saved in the cookie. If the session data exists, then its information will be updated and the cookie will be updated at the same time. Each update will regenerate the value of session_id.

By default, the Session Cookie will only be updated every 5 minutes, which will reduce the load on the processor. If you load the page repeatedly, you will find that the "last activity" time will not change until five minutes or more, which is the time when 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 composed of an array including the following information:
Unique user Session ID (this is a very strong random string calculated from the average amount of information, using MD5 encryption , the default is to regenerate every five minutes
User’s IP address
User browser information (take the first 50 characters)
The latest active timestamp.

The above data. It will be serialized and stored in the cookie using the following array format:

Copy code The 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 get any information of the session array through 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 need to use the following code:
$session_id = $this->session->userdata('session_id');
Note: If your target data does not exist , this function will return FALSE (boolean).

2. Add custom session data:
Suppose a specific user logs in to your website. When he passes the test, you can add his username and email to the session cookie. , this information can be used as global quantities without accessing the database.
You can pass a new user array to the session array through the following function:
$this->session->set_userdata($array);
$array is An associative array to store your new data. For example:

Copy code The code is as follows:

$newdata = array(
                                                                                                                                                                             ',
'email' => 'johndoe@some-site.com',
'logged_in' => TRUE
);
$this-> ;session->set_userdata( $newdata);

If you use the set_userdata() function below, you can add only one user data at a time.
$this->session->set_userdata('some_name', 'some_value');
Note: Cookies can only store 4KB of data, be careful not to exceed its capacity when using it. In particular, encryption will produce a longer data string than the original data, so 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, 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 of items to be deleted to this function.
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);

4. Store session data in the database:
When session data is available in the database, whenever a valid session is found from the user cookie, a database query will be executed to Match it. If the session IDs do not match, the session will be destroyed. Session IDs are never updated, they are only generated when a new session is created.
In order to store sessions, you must first create a data table. This is the basic structure required for the session class (for MySQL):

Copy code The code is as follows:

CREATE TABLE IF NOT EXISTS `ci_sessions` (
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.
Also make sure you have specified the data table name in the configuration file: $config['sess_table_name'] = 'ci_sessions';
Note: By default this table is called ci_sessions, but you can give it any name , as long as you update the application/config/config.php file to make sure it contains the name you gave it. Once you have created the data table, you can enable the database option in the config.php file like this:
$config['sess_use_database'] = TRUE;
Note: The Session class has built-in cleaning of expired sessions Garbage collection mechanism, so you don't need to write your own transactions to do this.

5. Destroy 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/config.php file:
Parameter Default Options Description
sess_cookie_name ci_session None You want to save the Session Cookie name.
sess_expiration 7200 None The number of seconds the session lasts. The default 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 boolean) Whether to encrypt session data.
sess_use_database FALSE TRUE/FALSE (Boolean boolean) Whether to store session data in the database. Before turning on this option, you must first create a database table.
sess_table_name ci_sessions Any valid SQL table name The name of the session database table.
sess_time_to_update 300 Time in seconds This option controls how often 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 operators and ISPs will dynamically change IPs, so setting this option to FALSE will make it possible to get a permanent session.
sess_match_useragent TRUE TRUE/FALSE (boolean) Whether to read session data according to the corresponding User Agent.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327825.htmlTechArticleThere are two methods of using session: 1 is the original session method of php, this is very simple, $ _SESSION['name']="name", then display where needed: echo $_SESSION['name']...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn