Home > Article > Backend Development > PHP creates and uses session cookie variables_PHP tutorial
// session start
session_start(); // Start a session. If you want to use the session program, you must add this sentence at the beginning.
$_SESSION[' user_id'] = '123';//Assign a value to a session variable. If the variable does not exist, create it
echo $_SESSION['user_id'];//Access the session variable
$ _SESSION = array();//Clear all session variables
session_destroy();//Clear session ID
// session end
// cookie start
setcookie(' user_id',123);//Create a cookie variable user_id=123
echo $_COOKIE['user_id'];//Accessing the cookie variable is the same as the variable variable
setcookie('user_id' ,0,time()-1);//Delete cookie variable
// codie end
// This code is not executable. It just lists all the usage methods here. The actual functions should be different. The use of different pages will be demonstrated in the following examples
?>
// session start
session_start(); // Start a session. If you want to use the session program, it is best to Be sure to add this sentence before
$_SESSION['user_id'] = '123';//Assign a value to a session variable. If the variable does not exist, create it
echo $_SESSION['user_id'];//Access session variables
$_SESSION = array();//Clear all session variables
session_destroy();//Clear session ID
// session end
// cookie start
setcookie('user_id',123);//Create a cookie variable user_id=123
echo $_COOKIE['user_id'];//Access cookie variables are the same as variable variables
setcookie('user_id',0,time()-1);//Delete cookie variable
// codie end
// This code is not runnable, but all usage methods are listed here. In fact, different functions should be used on different pages, which will be demonstrated in the following examples
?>
Cookie, session is WEB Ways for applications to maintain user state
Cookie is the saved client information, which is sent to the server when the client connects to the server.
Session is information stored on the server. From this perspective, session is more secure than cookie.
When a session is created, the server returns an encrypted session id to the client to identify the user. The session id is usually stored in a cookie. Passed by URL when unavailable
The above code demonstrates how to create and use session cookie variables