Home php教程 php手册 php下session过期时间的设置方法

php下session过期时间的设置方法

May 25, 2016 pm 04:48 PM

如果客户端没有禁用 Cookie,则 Cookie 在启动 Session 会话的时候扮演的是存储 Session ID 和 Session 生存期的角色。我们来手动设置 Session 的生存期:

例子,利用cooikes

<?php
session_start();
// 保存一天
$lifeTime = 24 * 3600;
setcookie(session_name() , session_id() , time() + $lifeTime, "/");
?>
Copy after login

PHP5 Session还提供了一个函数 session_set_cookie_params(); 来设置PHP5 Session的生存期的,该函数必须在 session_start() 函数调用之前调用:

<?php
// 保存一天
$lifeTime = 24 * 3600;
session_set_cookie_params($lifeTime);
session_start();
?>
Copy after login

php中还有一个ini_set可以设置session.gc_maxlifetime来设定Session的生存周期。例如:

<?php
ini_set(&#39;session.gc_maxlifetime&#39;, 3600); //设置时间
ini_get(&#39;session.gc_maxlifetime&#39;); //得到ini中设定值
?>
Copy after login

下面提供一个别人封装好的函数,但是我没有测试过,仅供参考:

<?php
function start_session($expire = 0) {
    if ($expire == 0) {
        $expire = ini_get(&#39;session.gc_maxlifetime&#39;);
    } else {
        ini_set(&#39;session.gc_maxlifetime&#39;, $expire);
    }
    if (empty($_COOKIE[&#39;PHPSESSID&#39;])) {
        session_set_cookie_params($expire);
        session_start();
    } else {
        session_start();
        setcookie(&#39;PHPSESSID&#39;, session_id() , time() + $expire);
    }
}
?>
Copy after login

使用方法:

加入start_session(600);//600秒以后过期。

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)