search
HomeBackend DevelopmentPHP Tutorial使用无限生命期Session的方法

在php4.0中加入了对session的支持,方便了我们很多程序,比如购物车等等!
在很多论坛中,Session也用于处理用户的登陆,记录下用户名和密码,使得用户不必每次都输入自己的用户名和密码!但是一般的Session的生命期有限,如果用户关闭了浏览器,就不能保存Session的变量了!那么怎么样可以实现Session的永久生命期呢?
大家知道,Session储存在服务器端,根据客户端提供的SessionID来得到这个用户的文件,然后读取文件,取得变量的值,SessionID可以使用客户端的Cookie或者Http1.1协议的Query_String(就是访问的URL的“?”后面的部分)来传送给服务器,然后服务器读取Session的目录……

要实现Session的永久生命期,首先需要了解一下php.ini关于Session的相关设置(打开php.ini文件,在“[Session]”部分):
1、session.use_cookies:默认的值是“1”,代表SessionID使用Cookie来传递,反之就是使用Query_String来传递;
2、session.name:这个就是SessionID储存的变量名称,可能是Cookie,也可能是Query_String来传递,默认值是“PHPSESSID”;
3、session.cookie_lifetime:这个代表SessionID在客户端Cookie储存的时间,默认是0,代表浏览器一关闭SessionID就作废……就是因为这个所以Session不能永久使用!
4、session.gc_maxlifetime:这个是Session数据在服务器端储存的时间,如果超过这个时间,那么Session数据就自动删除!
还有很多的设置,不过和本文相关的就是这些了,下面开始讲使用永久Session的原理和步骤。

前面说过,服务器通过SessionID来读取Session的数据,但是一般浏览器传送的SessionID在浏览器关闭后就没有了,那么我们只需要人为的设置SessionID并且保存下来,不就可以……
如果你拥有服务器的操作权限,那么设置这个非常非常的简单,只是需要进行如下的步骤:
1、把“session.use_cookies”设置为1,打开Cookie储存SessionID,不过默认就是1,一般不用修改;
2、把“session.cookie_lifetime”改为正无穷(当然没有正无穷的参数,不过999999999和正无穷也没有什么区别);
3、把“session.gc_maxlifetime”设置为和“session.cookie_lifetime”一样的时间;
设置完毕后,打开编辑器,输入如下的代码:
------------------------------------------------------------------------------------

session_start();
session_register('count');
$count++;
echo $count;
?>
------------------------------------------------------------------------------------
然后保存为“session_check.php”,用浏览器打开“session_check.php”,看看显示的是不是“1”,再关闭浏览器,然后再打开浏览器访问“session_check.php”,如果显示“2”,那么恭喜了,你已经成功;如果失败的话,请检查你前面的设置。

但是如果你没有服务器的操作权限,那就比较麻烦了,你需要通过PHP程序改写SessionID来实现永久的Session数据保存。查查php.net的函数手册,可以见到有“session_id”这个函数:如果没有设置参数,那么将返回当前的SessionID,如果设置了参数,就会将当前的SessionID设置为给出的值……
只要利用永久性的Cookie加上“session_id”函数,就可以实现永久Session数据保存了!
但是为了方便,我们需要知道服务器设置的“session.name”,但是一般用户都没有权限查看服务器的php.ini设置,不过PHP提供了一个非常好的函数“phpinfo”,利用这个可以查看几乎所有的PHP信息!
------------------------------------------------------------------------------------
PHP相关信息显示

------------------------------------------------------------------------------------
打开编辑器,输入上面的代码,然后在浏览器中运行这个程序,会见到PHP的相关信息(如图1所示)。其中有一项“session.name”的参数(图中已经标出),这个就是我们需要的服务器“session.name”,一般是“PHPSESSID”。
记下了SessionID的名称后,我们就可以实现永久的Session数据储存了!
打开编辑器,输入下面的代码:
------------------------------------------------------------------------------------

session_start(); // 启动Session
session_register('count'); // 注册Session变量Count
if(isset($PHPSESSID)) {
session_id($PHPSESSID);
} // 如果设置了$PHPSESSID,就将SessionID赋值为$PHPSESSID,否则生成SessionID
$PHPSESSID = session_id(); // 取得当前的SessionID
$count++; // 变量count加1
setcookie('PHPSESSID', $PHPSESSID, time()+3156000); // 储存SessionID到Cookie中
echo $count; // 显示Session变量count的值
?>
------------------------------------------------------------------------------------

保存之后,利用和刚才拥有服务器权限时候的检测一样的方法,检测是否成功的保存了SessionID。


后记:
其实真正的永久储存是不可能的,因为Cookie的保存时间有限,而服务器的空间也有限……但是对于一些需要保存时间比较长的站点,以上方法就已经足够了!关于Session的其他应用,可以参见zphp.com的文章。
最后,笔者的调试环境:Windows98DigExt(SE)+Apache+PHP 4.04。

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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software