This article mainly introduces sessionhow to store variables and how to delete variables in PHP.
First of all, everyone needs to understand, What does session mean in PHP? What is the use?
session in Chinese can be expressed as "conversation". Its original meaning refers to a series of actions/messages that have a beginning and an end. For example, a user asks a question and is then answered. Such a complete conversation is quite in one session.
The PHP session variable is used to store information about the user session, or to change the settings of the user session. The information held by the Session variable is single-user and available to all pages in the application.
But session information is temporary and will be deleted after the user leaves the website. If you need to store information permanently, you need to store the data in a database.
Then below we will combine simple code examples to introduce you to the basic usage of sessions in PHP, storing variables and deleting variables.
1. Session storage variables
When you need to store user information in the session, you must first open the session.
The code example is as follows:
<?php session_start(); $name="123"; $_SESSION['username']=$name; $_SESSION['password']=$name; echo $_SESSION['password'];
Here we first open the session, and then store the variable $name into the session. Through echo output, the test results are as follows:
session_start() will create a new session or reuse an existing session.
2. Delete variables from session
1. Use unset()
<?php session_start(); $name="123"; $_SESSION['username']=$name; unset($_SESSION['username']); echo $_SESSION['username'];
The echo test results are as follows:
unset() Destroys the specified variable.
The behavior of unset() in a function will vary depending on the type of variable you want to destroy.
2. Use session_destroy()
session_destroy();
session_destroy() to destroy all data in the current session, but it will not reset the global variables associated with the current session, nor Session cookies are not reset. If session variables need to be used again, the session_start() function must be called again.
This article will introduce the method of storing variables and deleting variables in session in PHP. It is also very simple. I hope it will be helpful to friends in need!
If you want to know more about PHP, you can follow the PHP Chinese websitePHP Video Tutorial, everyone is welcome to refer to and learn!
The above is the detailed content of How to store and delete variables in session in PHP? (Pictures + Videos). For more information, please follow other related articles on the PHP Chinese website!