Home Backend Development PHP Tutorial How to set up, obtain and delete Session in PHP?

How to set up, obtain and delete Session in PHP?

Oct 26, 2021 am 11:59 AM
php session

In the previous article, I brought you "How to create, read and delete cookies in PHP? ", which introduces in detail how to create, read and delete cookies in PHP. In this article, we will take a look at setting, obtaining and clearing sessions in PHP. I hope everyone has to help!

How to set up, obtain and delete Session in PHP?

In the previous article, we introduced the cookie used by the client to store user data. In this article, let’s take a look at its use in PHP. Very important session, session is a server-side mechanism, which is also used to save information. Compared with cookies saved on the client, users cannot disable sessions saved on the server side. The same client Every time the client interacts with the server, it does not need to return all cookie values ​​every time. It only needs to return an ID. This ID is generated when the server is accessed for the first time and is unique.

Then let’s take a look at what a session is and how to set, obtain and delete a session

What is a session

session in Chinese means session, which is used to store user-related information, which is similar to cookies, such as user names, personalized settings, etc., but is different from cookies What's interesting is that cookies save data on the client's computer and can be disabled by the user; sessions save data on the server system. The web page is a stateless program connection and cannot record the user's status, so it is particularly important to record the user's relevant information through the session.

When a session is opened, PHP will randomly create a sessionID, and each user's sessionID is unique. This sessionID will be saved on both the client and the server, in the specified directory where cookies will be used on the client; on the server, it will be saved in the form of recalled text in the specified session directory.

Compared with cookies, sessions have many advantages:

Because session data is not passed back and forth between the client and the server, usually the session is still More secure; session can store much more information than cookies; users can disable cookies, but there are ways to make sessions work normally.

After understanding what a session is, let’s take a look at how to open a session.

Opensession

Unlike cookies, cookies can be created directly, but sessions must be started before using them , the purpose is to allow the core program in PHP to preload the session-related built-in environment into memory.

In PHP, the purpose of opening the session can be achieved through the session_start() function. The syntax format of the function session_start() is as follows:

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

What needs to be paid attention to Yes:

$options is an optional function and an associative array, and the keys in this array do not need to contain the session. prefix.

The example is as follows:

<?php
    session_start([
        &#39;cookie_lifetime&#39; => 60*60*24,  // 设置 cookie 的有效时间为 1 天
    ]);
    echo &#39;Session ID 为:&#39;.$_COOKIE[&#39;PHPSESSID&#39;];
?>
Copy after login

Output result:

How to set up, obtain and delete Session in PHP?

It should be noted that: call session_start () The function will generate a unique Session ID and save it in the browser's Cookie. The default name is "PHPSESSID". At the same time, a Session file consisting of "sess_" plus Session ID is generated in the local directory to store the data in the Session. The output result is:

How to set up, obtain and delete Session in PHP?

Through the above example , you have learned how to open the session, then let’s take a look at how to set and get the session

Setting and gettingsession

In the above, after starting the session, if you want to use the session variable, you need to set and obtain the data in the session. To complete this, you need to complete it through the $_SESSION array. . Before using $_SESSION, you must first try the session_start() function to open the session.

$_SESSION is an associative array, which has the same meaning as a normal associative array key-value pair. The syntax format for setting Session is as follows:

$_SESSION[名称] = 值;
Copy after login

The example is as follows:

<?php
    session_start();
    $str = &#39;好好学习&#39;;
    $arr = [&#39;Session&#39;,&#39;$_SESSION&#39;];
    $_SESSION[&#39;study&#39;]  = $str;
    $_SESSION[&#39;study1&#39;]   = &#39;天天向上&#39;;
    $_SESSION[&#39;title&#39;] = $arr;
    foreach ($_SESSION as $key => $value) {
        if(is_array($value)){
            echo $key.&#39;:&#39;;
            print_r($value);
        }else{
            echo $key.&#39; = &#39;.$value.&#39;<br>&#39;;
        }
    }
?>
Copy after login

Output result:

How to set up, obtain and delete Session in PHP?

After running, you need to pay attention to: Save these variables or arrays to $_SESSION, and also save them to a file named by "sess_" and Session ID on the server side. The location of this file can be modified by modifying the php.ini configuration file or using session.save_path configuration.

We have already learned how to open, set and obtain the session. Next, let’s take a look at how to delete the session.

Delete a single session

删除单个session元素需要通过unset()函数,该函数可以释放指定的变量,相当于直接注销掉数组中的元素,他的语法格式如下:

unset(mixed $var [, mixed $...])
Copy after login

其中需要注意的是:

$var 为要释放的变量,unset() 函数可以接收多个参数,参数之间使用,分隔。

实例如下:

<?php
    session_start();
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    $str = &#39;好好学习&#39;;
    $arr = [&#39;删除 Session&#39;,&#39;$_SESSION&#39;];
    $_SESSION[&#39;study&#39;]  = $str;
    $_SESSION[&#39;study1&#39;]   = &#39;天天向上&#39;;
    $_SESSION[&#39;title&#39;] = $arr;
    echo &#39;定义一个 Session,如下所示:<br>&#39;;
    print_r($_SESSION);
    echo &#39;删除 Session 中名为 title 的元素:<br>&#39;;
    unset($_SESSION[&#39;title&#39;]);
    print_r($_SESSION);
?>
Copy after login

输出结果:

How to set up, obtain and delete Session in PHP?

如此便通过unset()函数完成了删除session单个元素了。

删除session多个元素

如果想要一次性删除多个 Session 元素,即一次注销所有的会话变量,可以通过将一个空的数组赋值给 $_SESSION 来实现

实例如下:

<?php
    session_start();
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    $str = &#39;好好学习&#39;;
    $arr = [&#39;删除 Session&#39;,&#39;$_SESSION&#39;];
    $_SESSION[&#39;study&#39;]  = $str;
    $_SESSION[&#39;study1&#39;]   = &#39;天天向上&#39;;
    $_SESSION[&#39;title&#39;] = $arr;
    echo &#39;定义一个 Session,如下所示:<br>&#39;;
    print_r($_SESSION);
    echo &#39;删除 Session 中名为 title 的元素:<br>&#39;;
    $_SESSION = array();
    print_r($_SESSION);
?>
Copy after login

通过将一个空的数组赋值给 $_SESSION 输出结果:

How to set up, obtain and delete Session in PHP?

还有一种方法就是通过session_unset() 函数来释放session中的所有元素,实例如下:

<?php
    session_start();
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    $str = &#39;好好学习&#39;;
    $arr = [&#39;删除 Session&#39;,&#39;$_SESSION&#39;];
    $_SESSION[&#39;study&#39;]  = $str;
    $_SESSION[&#39;study1&#39;]   = &#39;天天向上&#39;;
    $_SESSION[&#39;title&#39;] = $arr;
    echo &#39;定义一个 Session,如下所示:<br>&#39;;
    print_r($_SESSION);
    echo &#39;删除 Session 中名为 title 的元素:<br>&#39;;
    session_unset();
    print_r($_SESSION);
?>
Copy after login

输出结果与上述实例的结果相同,由此我们便通过两种方法可以删除session多个元素了。

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

The above is the detailed content of How to set up, obtain and delete Session in PHP?. 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)

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,

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

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

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