How to set up, obtain and delete Session in PHP?
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!
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()])
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([ 'cookie_lifetime' => 60*60*24, // 设置 cookie 的有效时间为 1 天 ]); echo 'Session ID 为:'.$_COOKIE['PHPSESSID']; ?>
Output result:
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:
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[名称] = 值;
The example is as follows:
<?php session_start(); $str = '好好学习'; $arr = ['Session','$_SESSION']; $_SESSION['study'] = $str; $_SESSION['study1'] = '天天向上'; $_SESSION['title'] = $arr; foreach ($_SESSION as $key => $value) { if(is_array($value)){ echo $key.':'; print_r($value); }else{ echo $key.' = '.$value.'<br>'; } } ?>
Output result:
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 $...])
其中需要注意的是:
$var
为要释放的变量,unset()
函数可以接收多个参数,参数之间使用,
分隔。
实例如下:
<?php session_start(); echo '<pre class="brush:php;toolbar:false">'; $str = '好好学习'; $arr = ['删除 Session','$_SESSION']; $_SESSION['study'] = $str; $_SESSION['study1'] = '天天向上'; $_SESSION['title'] = $arr; echo '定义一个 Session,如下所示:<br>'; print_r($_SESSION); echo '删除 Session 中名为 title 的元素:<br>'; unset($_SESSION['title']); print_r($_SESSION); ?>
输出结果:
如此便通过unset()函数完成了删除session单个元素了。
删除session多个元素
如果想要一次性删除多个 Session 元素,即一次注销所有的会话变量,可以通过将一个空的数组赋值给 $_SESSION
来实现
实例如下:
<?php session_start(); echo '<pre class="brush:php;toolbar:false">'; $str = '好好学习'; $arr = ['删除 Session','$_SESSION']; $_SESSION['study'] = $str; $_SESSION['study1'] = '天天向上'; $_SESSION['title'] = $arr; echo '定义一个 Session,如下所示:<br>'; print_r($_SESSION); echo '删除 Session 中名为 title 的元素:<br>'; $_SESSION = array(); print_r($_SESSION); ?>
通过将一个空的数组赋值给 $_SESSION 输出结果:
还有一种方法就是通过session_unset() 函数来释放session中的所有元素,实例如下:
<?php session_start(); echo '<pre class="brush:php;toolbar:false">'; $str = '好好学习'; $arr = ['删除 Session','$_SESSION']; $_SESSION['study'] = $str; $_SESSION['study1'] = '天天向上'; $_SESSION['title'] = $arr; echo '定义一个 Session,如下所示:<br>'; print_r($_SESSION); echo '删除 Session 中名为 title 的元素:<br>'; session_unset(); print_r($_SESSION); ?>
输出结果与上述实例的结果相同,由此我们便通过两种方法可以删除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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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,

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

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

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 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.
