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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.