Home php教程 php手册 解析php框架codeigniter中如何使用框架的session

解析php框架codeigniter中如何使用框架的session

Jun 13, 2016 am 11:45 AM
codeigniter php session use how have frame of parse

里面有两种session的使用方法:
1是php的原始的session使用方法,这个很简单,$_SESSION['name']="name",然后在需要的地方显示:echo $_SESSION['name'];
2是codeigniter这个框架的一个方法:
下面就详细讲解如何使用这个有点点复杂的方法:
首先,在\ci\application\config下面的config.php文件中找到:$config['encryption_key'] = '';这个里面随便填什么值都可以,但是不能为空。一般是英文啊,不要钻牛角尖。
接着在\ci\application\config下面的auto.php文件中找到:$autoload['libraries'] = array('');里面要填写:$autoload['libraries'] = array('session');或者在适当的地方如control文件夹里面的相应文件中(一般是在构造方法中)写:$this->load->library('session');这样也行。
现在环境配置好了,现在就是写代码了:
在需要放入session的地方写:
$this->session->set_userdata('name','yang');
这样session里面就有了值了。
显示值:
echo $this->session->userdata('name');
如果是array,则:
$newdata = array(
                   'username'  => 'johndoe',
                   'email'     => 'johndoe@some-site.com',
                   'logged_in' => TRUE
               );
$this->session->set_userdata($newdata);
以下是转载的别人的详细的有点废话的相关知识:
Sessions会在每个页面载入后开始运行,所以session类必须首先被初始化。

1、您可以在控制器中初始化,也可以在系统中自动加载(译者注:在autoload.php设定)$autoload['libraries'] = array('session');

2、要在您的控制器构造函数中初始化session类,您可以使用 $this->load->library 函数:$this->load->library('session');一旦被载入, session就可以这样使用: $this->session。
session类的绝大部分都会在后台运行,所以初始化session时,它session数据会被自动读取、创建和更新。

Sessions 是怎样工作的?
需要知道的非常重要的一点就是,session类一旦被初始化,它就会自动运行。对于后面的事情,您可以完全不作理会。正如您将会在下面看到的一样,您可以正常使用session来工作,甚至还可以添加自己的session数据,而在这一切的过程中,读、写和更新的操作都是自动完成的。

当页面载入后,session类就会检查用户的cookie中是否存在有效的session数据。如果session数据不存在(或者已经过期),那么就会创建一个新的session并把他保存在cookie中。如果session数据存在,那么他的信息就会被更新,同时cookie也会被同时更新。每次更新都会重新生成session_id的值。

默认情况下, Session Cookie 每隔 5 分钟才会更新一次,这样会减少对处理器的负荷。如果你重复的装载页面, 你会发现"上次活动"的时间在五分钟,或多余五分钟的时候才会变化,也就是 cookie上次被写入的时间。 这个时间可以通过设置 application/config/config.php 文件里的 $config['sess_time_to_update'] 行来改变。

一个 session 是由一个包括下列信息的数组组成的:
唯一的用户Session ID (这是一个平均信息量统计出来的非常坚固的随机字符串,使用MD5加密,默认是每五分钟就重新生成一次。
用户的 IP 地址
用户浏览器信息(取前50个字符)
最新的一个活跃时间戳.
以上数据将会用以下数组格式序列化并存到cookie里:

复制代码 代码如下:


[array]
(
     'session_id'    => random hash,
     'ip_address'    => 'string - user IP address',
     'user_agent'    => 'string - user agent data',
     'last_activity' => timestamp
)


1、取得 Session 数据:
可以通过如下的函数来得到 session 数组的任何信息:
$this->session->userdata('item');
item 是数组里的相对应数据的索引。例如,想要获得 session ID, 你要使用如下的代码:
$session_id = $this->session->userdata('session_id');
注意: 如果你的目标数据不存在的话,这个函数会返回 FALSE (布尔值boolean)。

2、添加自定义的 Session 数据:
假设,有个特定用户登陆到你的网站, 当他通过检测后 你可以添加他的用户名和电子邮件到 session cookie 中,这些信息可以在不去访问数据库的情况下,当成全局量来使用。
通过以下函数,你可以传递一个新的用户数组到 session 数组中:
$this->session->set_userdata($array);
$array 是一个结合数组,用来存储你的新数据。例如 :

复制代码 代码如下:


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


如果使用下面 set_userdata()函数的写法,可以每次只添加一个用户数据。
$this->session->set_userdata('some_name', 'some_value');
注意: Cookies 只能存储 4KB 的数据, 使用时要小心超出它的容量。特别指出的是,加密会产生比原数据更长的数据字符串,所以一定要当心你要存放数据的大小。

3、删除 Session 数据:正如使用 set_userdata() 是用来添加信息到 session 中,而通过向unset_userdata() 函数中传递 session key 可以用来删除这些信息。例如, 你想要从 session 信息里去掉 'some_name':
$this->session->unset_userdata('some_name');
也可以给这个函数传一个要删除项的关联数组。
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);

4、将 Session 数据存入数据库:
当session 数据在数据库中可用时,每当从用户cookie中发现一个有效的session,一个数据库查询就会被执行以匹配它。如果 session ID 不相配,session 就会被销毁。Session ID永远不会更新,它们只会在一个新的会话创建时生成。
为了存储session,你必须先创建一个数据表。这是 session 类所需的基本结构(用于MySQL的):

复制代码 代码如下:


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) );


一旦启用了,Session类就会在数据库中存储session数据。
同时确保你已经在配置文件中指定了数据表名:$config['sess_table_name'] = 'ci_sessions';
注意: 默认情况下这个表叫做 ci_sessions, 但是你可以给它指定任意名字,只要你更新了 application/config/config.php 文件以确保它包含了你所起的名字。一旦你创建了数据表,你就可以像下面这样在config.php文件中启用数据库选项:
$config['sess_use_database'] = TRUE;
注意: Session类已经内置了清除过期session的垃圾回收机制,因此你不需要编写你自己的事务来做这个。

5、销毁 Session
要清除当前 session:$this->session->sess_destroy();
Session 的参数

6、你可以在application/config/config.php 文件中找到以下的 Session 相关的参数:
参数     默认     选项     描述
sess_cookie_name     ci_session     无     你想要保存 Session Cookie 的名字。
sess_expiration     7200     无     session 持续的秒数。默认是2个小时(7200秒)。如果将这个数值设为: 0,就可以得到 永久 session。
sess_expire_on_close     FALSE     TRUE/FALSE (boolean)     这个选项决定当浏览器窗口关闭时是否自动使session过期。
sess_encrypt_cookie     FALSE     TRUE/FALSE (布尔值boolean)     是否对 session 数据加密.
sess_use_database     FALSE     TRUE/FALSE (布尔值boolean)     是否将 session 数据存放入数据库中。在开启这个选项前,你要先创建一个数据库表。
sess_table_name     ci_sessions     任何有效的 SQL 表名     session 数据库表的名字。
sess_time_to_update     300     时间以秒计算     这个选项控制 session 类多久会产生一个新的session 和 session id。
sess_match_ip     FALSE     TRUE/FALSE (布尔值boolean)     是否通过用户的IP地址来读取 session 的数据。 注意 ,有些网络运行商 ISPs 会动态的改变IP, 所以将这个选项设为 FALSE, 才有可能得到永久的 session。
sess_match_useragent     TRUE     TRUE/FALSE (布尔值boolean)     是否要按照对应的 User Agent 来读取 session 数据。

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
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,

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.

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

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles