Home > Backend Development > PHP Tutorial > php session session (topic)

php session session (topic)

PHPz
Release: 2023-04-09 07:40:01
Original
7244 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template