PHP logout效能

Jun 13, 2016 pm 12:43 PM
cookie php session start the

PHP logout功能

php手册写道
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

?

百度知道 写道
session 是一个会话,在session_start() 的时候建立。
$_SESSION 是一个全局数组,和其他的全局数组没有任何区别。只是php在创建一个会话的时候,会顺便创建一个全局数组来保存会话的内容,这个数组又刚好叫$_SESSION,和我们自己去创建的其他数组没有什么不一样。
session_start() 执行的时候,开启了会话,首先是如果该会话没有被创建,则在系统的tmp目录中创建了session文件(默认,可自定义),并且在当前会话的执行脚本创建全局数组$_SESSION,h这时的$_SESSION是一个空数组。如果会话存在,则读取session文件中的内容,建立$_SESSION数组。
session_destroy() ,手册中明确的说道:destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.
不会删除 session 的全局变量和 session相关cookie,只是结束了这次会话。作为一个普普通通的全局变量,如果我们不需要乐得话,就将他 unset() 掉。如果想再次开启会话,就需要再一次session_start(),但是session_start() 重新建立会话,会重新初始化$_SESSION数组,session_start()之后$_SESSION 就又是一个空数组了。

?

1

2

3

4

5

6

7

8

<?php

session_start();

echo var_dump($_SESSION);

session_destroy();

echo var_dump($_SESSION);

session_start();

echo var_dump($_SESSION);

?>

Copy after login

?结果是

1

2

3

array(4) { ["username"]=> string(2) "xx" ["user_id"]=> string(1) "7" ["user_level"]=> string(1) "0" ["signed_in"]=> bool(true) }

array(4) { ["username"]=> string(2) "xx" ["user_id"]=> string(1) "7" ["user_level"]=> string(1) "0" ["signed_in"]=> bool(true) }

array(0) { }

Copy after login

?

http://www.nowamagic.net/php/php_SessionPrinciple.php 写道


PHP SESSION原理

我们知道,session是在服务器端保持用户会话数据的一种方法,对应的cookie是在客户端保持用户数据。HTTP协议是一种无状态协议,服务器响应完之后就失去了与浏览器的联系,最早,Netscape将cookie引入浏览器,使得数据可以客户端跨页面交换,那么服务器是如何记住众多用户的会话数据呢?

首先要将客户端和服务器端建立一一联系,每个客户端都得有一个唯一标识,这样服务器才能识别出来。建议唯一标识的方法有两种:cookie或者通过GET方式指定。默认配置的PHP使用session的时会建立一个名叫”PHPSESSID”的cookie(可以通过php.ini修改session.name值指定),如果客户端禁用cookie,你也可以指定通过GET方式把session id传到服务器(修改php.ini中session.use_trans_sid等参数)。

我们查看服务器端session.save_path目录会发现很多类似sess_vv9lpgf0nmkurgvkba1vbvj915这样的文件,这个其实就是session id “vv9lpgf0nmkurgvkba1vbvj915″对应的数据。真相就在这里,客户端将session id传递到服务器,服务器根据session id找到对应的文件,读取的时候对文件内容进行反序列化就得到session的值,保存的时候先序列化再写入。

事实就是这样,所以如果服务器不支持session或者你想自定义session,完全可以DIY,通过PHP的uniqid生成永不重复的session id,然后找个地方存储session的内容即可,你也可以学flickr把session存储在MySQL数据库中。
使用session之前为什么必须先执行session_start()?

了解的原理之后,所谓的session其实就是客户端一个session id服务器端一个session file,新建session之前执行session_start()是告诉服务器要种一个cookie以及准备好session文件,要不然你的session内容怎么存;读取session之前执行session_start()是告诉服务器,赶紧根据session id把session文件反序列化。

只有一个session函数可以在session_start()之前执行,session_name():读取或指定session名称(比如默认的就是”PHPSESSID”),这个当然要在session_start之前执行。
session影响系统性能

session在大访问量网站上确实影响系统性能,影响性能的原因之一由文件系统设计造成,在同一个目录下超过10000个文件时,文件的定位将非常耗时,PHP支持session目录hash,我们可以通过修改php.ini中session.save_path = “2;/path/to/session/dir”,那么session将存储在两级子目录中,每个目录有16个子目录[0~f],不过好像PHP session不支持创建目录,你需要事先把那么些目录创建好 。

还有一个问题就是小文件的效率问题,一般我们的session数据都不会太大(1~2K),如果有大量这样1~2K的文件在磁盘上,IO效率肯定会很差,PHP手册上建议使用Reiserfs文件系统,不过Reiserfs的前景堪忧,Reiserfs的作者把媳妇给杀了,SuSE也抛弃了Reiserfs。

其实还有很多中存储session的方式,可以通过php -i|grep “Registered save handlers”查看,比如Registered save handlers => files user sqlite eaccelerator可以通过文件、用户、sqlite、eaccelerator来存,如果服务器装了memcached,还有会mmcache的选项。当然还有很多,比如MySQL、PostgreSQL等等。都是不错的选择。
session的同步

我们前端可能有很多台服务器,用户在A服务器上登录了,种下了session信息,然后访问网站的某些页面没准跳到B服务器上去了,如果这个时候B服务器上没有session信息又没有做特殊处理,可能就会出问题了。

session同步有很多种,如果你是存储在memcached或者MySQL中,那就很容易了,指定到同样的位置即可,如果是文件形式的,你可以用NFS统一存储。

还有一种方式是通过加密的cookie来实现,用户在A服务器上登录成功,在用户的浏览器上种上一个加密的cookie,当用户访问B服务器时,检查有无session,如果有当然没问题,如果没有,就去检验cookie是否有效,cookie有效的话就在B服务器上重建session。这种方法其实很有用,如果网站有很多个子频道,服务器也不在一个机房,session没办法同步又想做统一登录那就太有用了。

当然还有一种方法就是在负载均衡那一层保持会话,把访问者绑定在某个服务器上,他的所有访问都在那个服务器上就不需要session同步了,这些都是运维层面的东西。就说这么多吧,根据自己的应用来选择使用session,不要因为大家都说session影响系统性能就畏首畏尾,知道问题,解决问题才是关键,惹不起躲得起不适合这里。

?删除session和相关的cookie的方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?php

// Initialize the session.

// If you are using session_name("something"), don't forget it now!

session_start();

 

// Unset all of the session variables.

$_SESSION = array();

 

// If it's desired to kill the session, also delete the session cookie.

// Note: This will destroy the session, and not just the session data!

if (ini_get("session.use_cookies")) {

    $params = session_get_cookie_params();

    setcookie(session_name(), '', time() - 42000,

        $params["path"], $params["domain"],

        $params["secure"], $params["httponly"]

    );

}

 

// Finally, destroy the session.

session_destroy();

?>

Copy after login

?

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