Table of Contents
#1: What is PHP Session?
Session mechanism
PHP Session key points
2: Introduction to basic functions of PHP Session
3: Use case
四:PHP Session 视频教程
五:PHP Session 精选技术文章
Home Backend Development PHP Tutorial php session session (topic)

php session session (topic)

Jul 11, 2020 pm 05:55 PM
php session

php session topics include PHP Session concepts, basic function usage, PHP Session use cases, PHP Session video tutorials and related selected articles. Welcome to learn!

php session session (topic)

#1: What is PHP Session?

Official explanation: Session mechanism (Session) is used in PHP to maintain relevant data when users continuously access web applications, helping to create highly customized program, increasing the attractiveness of the site.

To understand what php session is, you must first understand what the session mechanism is

Session mechanism

HTTP is based on a connectionless network protocol. A visit is brand new to the server

If you remember the visitor and record the connection status, you can improve the user experience and complete many personalized functions, such as user login, shopping cart, etc.

In fact, the way for the server to remember the user is very simple, just like in life, when we apply for a membership card, it is the same.

There are two places where the membership card is stored, either on you or Saved to the merchant's computer

So, user information on the network will also be saved in two places: the browser (client) and the server

What is saved to the browser is called: cookie

The name saved to the server is: session

Extended knowledge: The difference between session and cookie in php

Related topics: php cookie (graphic topic)

PHP Session key points

  • Save on the server side

  • Variable: $_SESSION

  • Variable filter: filter_input(INPUT_SESSION, key)

  • Set using dedicated function: setcookie(name, value, expiration time)

  • needs to be completed in two steps to take effect: first issue the command to the browser, and then the browser completes the cookie writing

2: Introduction to basic functions of PHP Session

1.session_create_id

Create a new session id

session_create_id ([ string $prefix ] ) : string
Copy after login

Parameters

  • prefix: If prefix is ​​specified, the new session id will be prefixed by prefix. All characters are not allowed in the session id. Characters in the range a-z a-z 0-9, , (comma) and - (minus sign) are allowed.

Return value

Returns the new conflict-free session id of the current session. If it is used without an active session, conflict checking is ignored.

2.session_destroy

Destroy all data in a session

session_destroy ( void ) : bool
Copy after login

Return value

Return TRUE when successful, or when Returns FALSE on failure.

3.session_id

Get/Set the current session ID

session_id ([ string $id ] ) : string
Copy after login

Parameters

  • id: if If the value of the id parameter is specified, the specified value is used as the session ID. The session_id() function must be called before the session_start() function is called. Different session managers have different restrictions on the characters that can be used in session IDs. For example, the file session manager only allows the following characters in the session ID: a-z A-Z 0-9 , (comma) and - (minus sign)

Return Value

Return Current session ID. If there is no current session, an empty string ("") is returned.

4.session_name

Read/set session name

session_name ([ string $name ] ) : string
Copy after login

Parameters

  • name: use Session name in cookie or URL, for example: PHPSESSID. Only letters and numbers can be used as the session name. It is recommended that it be as short as possible and that it is a meaningful name (for users who have enabled cookie warnings, it is easier for them to determine whether to allow this cookie). If the name parameter is specified, the current session will also use the specified value as its name.

Return value

Returns the current session name. If the name parameter is specified, this function updates the session name and returns the original session name.

5.session_start

Start a new session or reuse an existing one

session_start ([ array $options = array() ] ) : bool
Copy after login

Parameters

  • options : This parameter is an associative array whose items, if provided, will be used to override the configuration items in the session configuration directive. The keys in this array need not contain the session. prefix.

Return value

Returns TRUE if the session is successfully started, otherwise returns FALSE

6.session_status

Return current session status

session_status ( void ) : int
Copy after login

Return value

PHP_SESSION_DISABLED The session is disabled.

PHP_SESSION_NONE Session is enabled, but the current session does not exist.

PHP_SESSION_ACTIVE The session is enabled and the current session exists.

7.session_unset

Release all session variables

session_unset ( void ) : void
Copy after login

3: Use case

1. Basic session operations

Commonly used basic operations of PHP Session

<?php
//开启session会话
session_start();


//设置session
$_SESSION[&#39;username&#39;] = &#39;adminuser&#39;;


//获取session
$username = $_SESSION[&#39;username&#39;];


//删除session
unset($_SESSION[&#39;username&#39;]);


//清空session
session_unset();
//或
$_SESSION = [];


//销毁session
session_destroy();
Copy after login

2. Solution to disabling cookies in the browser

cookie和session的区别在于cookie是保存在客户端的,而session是存储在服务端中。它们都有生存时间的设置,session比cookie更安全。

当服务端与客户端通信后会生成会话后,会建立一个和浏览器的唯一会话PHPSESSID。这个id会在服务端保存,也会用cookie形式保存在客户端中。

禁用cookie后session不能把唯一id通过cookie方式在客户端中进行存储,这时候php会在浏览器地址栏中以url明文get的方式来传递phpsessionid,来进行客户端和服务端的唯一识别通信。

这样一来程序的安全性大大降低了。所有在php.ini默认是关闭通过地址栏传递phpsessionid的,如果没开启就不能使用session,所以需要php.ini配置支持才行。

session.use_only_cookies = 1; // 开启仅使用cookies存放会话id           
session.use_trans_sid = 1;     // 允许Sessionid通过URL明文传输,默认为0关闭
Copy after login

或者使用代码来实现

/**
 * 兼容 php7.1 以下版本
 */
if (!function_exists(&#39;session_create_id&#39;)) {
    function session_create_id()
    {
        return uniqid();
    }
}

//获取SESSION_ID
$session_id = isset($_GET[&#39;SESSION_ID&#39;]) ? $_GET[&#39;SESSION_ID&#39;] : session_create_id();

//设置 SESSION_ID
session_id($session_id);

//开启session
session_start();

$_SESSION[&#39;user&#39;] = &#39;user01&#39;;

//echo $_SESSION[&#39;user&#39;];

echo $session_id;
Copy after login

3、浏览计数器

利用 session 机制可以实现 记录用户的访问页面的次数,代码如下:

<?php
//开启session
session_start();

//判断是否设置浏览数
if (isset($_SESSION[&#39;view_num&#39;])) {
    //如果设置 浏览数加 1
    $_SESSION[&#39;view_num&#39;] = $_SESSION[&#39;view_num&#39;] + 1;
} else {
    //如果未设置 设置浏览数为 1
    $_SESSION[&#39;view_num&#39;] = 1;
}

die(&#39;当前浏览数为:&#39; . $_SESSION[&#39;view_num&#39;]);
?>
Copy after login

4、使用 session 实现登录功能

对于 Cookie 来说,假设我们要验证用户是否登陆,就必须在 Cookie 中保存用户名和密码(可能是 md5 加密后字符串),并在每次请求页面的时候进行验证。

如果用户名和密码存储在数据库,每次都要执行一次数据库查询,给数据库造成多余的负担。因为我们并不能 只做一次验证。为什么呢?

因为客户端 Cookie 中的信息是有可能被修改的。假如你存储 $admin 变量来表示用户是否登陆,$admin 为 true 的时候表示登陆,为 false 的时候表示未登录,在第一次通过验证后将 $admin 等于 true 存储在 Cookie,下次就不用验证了,这样对么?错了,假如有人伪造一个值为 true 的 $admin 变量那不是就立即取的了管理权限么?非常的不安全。

而 Session 就不同了,Session 是存储在服务器端的,远程用户没办法修改 Session 文件的内容,因此我们可以单纯存储一个 $admin 变量来判断是否登陆,首次验证通过后设置 $admin 值为 true,以后判断该值是否为 true,假如不是,转入登陆界面,这样就可以减少很多数据库操作了。

而且可以减少每次为了验证 Cookie 而传递密码的不安全性了(Session 验证只需要传递一次,假如你没有使用 SSL 安全协议的话)。即使密码进行了 md5 加密,也是很容易被截获的。

当然使用 Session 还有很多优点,比如控制容易,可以按照用户自定义存储等(存储于数据库)。

下面是一个简单的用户登录示例:

<?php
session_start();

//判断是否登录
if (isset($_SESSION[&#39;login_user&#39;])) {
    die(&#39;已登录!当前登录用户为:&#39; . $_SESSION[&#39;login_user&#39;]);
}

//判断是否为POST请求
if ($_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {

    //检查是否输入用户名
    if (!isset($_POST[&#39;username&#39;]) || empty($_POST[&#39;username&#39;])) {
        die(&#39;请输入用户名!&#39;);
    }

    //检查是否输入密码
    if (!isset($_POST[&#39;password&#39;]) || empty($_POST[&#39;password&#39;])) {
        die(&#39;请输入密码!&#39;);
    }

    //模拟数据
    $data = [&#39;username&#39; => &#39;user01&#39;, &#39;password&#39; => md5(&#39;123456&#39;)];

    //检查用户名是否正确
    if ($_POST[&#39;username&#39;] === $data[&#39;username&#39;]) {
        //检查密码是否正确
        if (md5($_POST[&#39;password&#39;]) === $data[&#39;password&#39;]) {
            //保存登录状态
            $_SESSION[&#39;login_user&#39;] = $_POST[&#39;username&#39;];
            die(&#39;恭喜你登录成功!&#39;);
        }
    }

    //用户名或密码不正确
    die(&#39;用户名或密码不正确!&#39;);
}
?>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="=device-width, initial-scale=1.0">
    <title>用户登录</title>
</head>
<body>
<form action="./session02.php" method="post">
    <input type="text" name="username" placeholder="请输入用户名!">
    <input type="password" name="password" placeholder="请输入密码!">
    <button type="submit">登录</button>
</form>
</body>
</html>
Copy after login

四:PHP Session 视频教程

php session session (topic)

1.PHP中session如何存储及删除变量的

2.PHP如何用session来判断用户是否登录

3.PHP如何用session来记录用户登陆信息

4.php视频教程之PHP会话管理

5.PHP视频教程之会话控制session的工作机制

6.PHP高级视频教程之和session存储相关的一些面试题

7.ThinkPHP5基础讲解视频教程之Session的使用

8.ThinkPHP5基础讲解视频教程之Session的使用

9.PHP经典实战视频教程之SESSION示例(购物车)

10.会话管理视频教程

11.Blog项目实战之session原理

五:PHP Session 精选技术文章

1.PHP7中创建session和销毁session的方法

2.利用php设置一个严格控制过期时间的session

3.Three ways to clear the session in php

4.Detailed explanation of the steps for PHP to set up web cluster session synchronization

5.Detailed explanation of examples of judging user operation permissions through Session

6.Redis method of saving PHP Session

7.Laravel uses Redis sharing Session (detailed code explanation)

8.ThinkPHP6.0: Changes in Session and Cookie mechanisms

9.The implementation principle of Session ID in PHP Analysis

10.php implements the member login registration page with html plus Session and Cookie

11.php restores the session content through session_id

12.In-depth introduction to the main session configuration in PHP.ini

13.WeChat applet’s case of obtaining session_key and openid (picture)

14.Session sharing: How to realize session sharing in PHP and redis clusters

15.Introduction to the method of redis to realize session sharing

16.tp5 realizes logging in and saving the session, and then jumps to the page according to different role permissions

17.Understand the php session operating mechanism

18.Solution to the general situation when PHP cannot obtain SESSION information

19.Detailed explanation of steps to prevent repeated submission of forms in PHP Session

20. PHP’s method of keeping Session from expiring

21.PHP’s method of improving SESSION response speed

22.MemCache caching and Session ( Knowledge summary)

23.Comparison of several ways for the front-end to obtain session information

24.Detailed explanation of Laravel's method of processing session (session)

The above is the detailed content of php session session (topic). For more information, please follow other related articles on the PHP Chinese website!

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)

Memcached caching technology optimizes Session processing in PHP Memcached caching technology optimizes Session processing in PHP May 16, 2023 am 08:41 AM

Memcached is a commonly used caching technology that can greatly improve the performance of web applications. In PHP, the commonly used Session processing method is to store the Session file on the server's hard disk. However, this method is not optimal because the server's hard disk will become one of the performance bottlenecks. The use of Memcached caching technology can optimize Session processing in PHP and improve the performance of Web applications. Session in PHP

Comparative analysis of PHP Session cross-domain and cross-site request forgery Comparative analysis of PHP Session cross-domain and cross-site request forgery Oct 12, 2023 pm 12:58 PM

Comparative analysis of PHPSession cross-domain and cross-site request forgery With the development of the Internet, the security of web applications has become particularly important. PHPSession is a commonly used authentication and session tracking mechanism when developing web applications, while cross-domain requests and cross-site request forgery (CSRF) are two major security threats. In order to protect the security of user data and applications, developers need to understand the difference between Session cross-domain and CSRF, and adopt

Best practices for solving PHP Session cross-domain issues Best practices for solving PHP Session cross-domain issues Oct 12, 2023 pm 01:40 PM

Best Practices for Solving PHPSession Cross-Domain Issues With the development of the Internet, the development model of front-end and back-end separation is becoming more and more common. In this mode, the front-end and back-end may be deployed under different domain names, which leads to cross-domain problems. In the process of using PHP, cross-domain issues also involve Session delivery and management. This article will introduce the best practices for solving session cross-domain issues in PHP and provide specific code examples. Using CookiesUsing Cookies

Analyze PHP Session cross-domain error log processing Analyze PHP Session cross-domain error log processing Oct 12, 2023 pm 01:42 PM

PHPSession cross-domain error log processing When developing web applications, we often use PHP's Session function to track the user's status. However, in some cases, cross-domain errors may occur, resulting in the inability to access and operate Session data correctly. This article will introduce how to handle PHPSession cross-domain errors and provide specific code examples. What is PHPSession cross-domain error? Cross-domain error refers to the error in the browser

PHP Session cross-domain and cross-platform compatibility processing PHP Session cross-domain and cross-platform compatibility processing Oct 12, 2023 am 09:46 AM

PHPSession's cross-domain and cross-platform compatibility processing With the development of web applications, more and more developers are facing cross-domain problems. Cross-domain refers to a web page under one domain name requesting resources under another domain name. This increases the difficulty of development to a certain extent, especially for applications involving session (Session) management. It is a tricky problem. question. This article will introduce how to handle cross-domain session management in PHP and provide some specific code examples. Session Management is We

The relationship between PHP Session cross-domain and cross-site scripting attacks The relationship between PHP Session cross-domain and cross-site scripting attacks Oct 12, 2023 pm 12:58 PM

The relationship between PHPSession cross-domain and cross-site scripting attacks. With the widespread use of network applications, security issues have attracted increasing attention. When developing web applications, handling user sessions is a very common requirement. PHP provides a convenient session management mechanism - Session. However, Session also has some security issues, especially those related to cross-domain and cross-site scripting attacks. Cross-domain attack (Cross-Domain) refers to the attack through a website

Adaptability analysis of PHP Session cross-domain and multi-layer system architecture Adaptability analysis of PHP Session cross-domain and multi-layer system architecture Oct 12, 2023 pm 02:34 PM

Adaptability analysis of PHPSession cross-domain and multi-layer system architecture With the development of Internet technology, multi-layer system architecture is becoming more and more common in Web applications. In multi-layer system architecture, cross-domain access is a common requirement. The Session mechanism in PHP is also widely used in functions such as authentication and data sharing in Web applications. This article will deeply explore the cross-domain adaptability of PHPSession in multi-layer system architecture and provide specific code examples.

PHP Session cross-domain security audit and vulnerability mining PHP Session cross-domain security audit and vulnerability mining Oct 12, 2023 am 11:23 AM

PHPSession cross-domain security audit and vulnerability mining summary: With the development of the Internet, more and more websites are beginning to use PHPSession to manage user login status and data. However, due to the characteristics of PHPSession, it has some security risks, especially in the case of cross-domain access. This article will introduce the importance of cross-domain security auditing of PHPSession and provide some specific vulnerability mining code examples. 1. Introduction PHPSession is a kind of

See all articles