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

Jul 21, 2016 pm 03:03 PM
codeigniter php session use how have frame of parse

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles