Home > headlines > body text

How to use session in php

无忌哥哥
Release: 2020-07-25 11:59:21
Original
3806 people have browsed it

For details on how to use php session, see: php session session topic

* session session

* session is very similar to cookie, It just saves the user data to the page on the server

* But the query key is still on the browser, saved with a special cookie

* This special key is called: PHPSESSID( Session ID)

//The session must be opened before all html code is output to the browser

//session_start() will send a 32-bit hexadecimal PHPSESSID# to the browser

##//There must be no statements such as echo, print, include, or even blank lines before opening a session

session_start();
Copy after login

//Once the session is opened successfully, we can save the user's session information On the server

//All operations of the session are implemented through the super global variable $_SESSION

$_SESSION['user_name'] = 'admin';
$_SESSION['user_id'] = 1;
Copy after login

//Tmp/php/32-bit text file corresponding to PHPSESSID on the server

//user_name|s:5:"admin";user_id|i:1;

//Syntax: variable name|type: value; use a semicolon between each session variable separated, the string type will have a length prompt

//Session access is very similar to cookies, use the $_SESSION array directly

echo $_SESSION['user_name'];
Copy after login

//Update

$_SESSION['user_name'] = 'peter';
echo $_SESSION['user_name'];
Copy after login

//Delete

//1. Delete a single session variable

unset($_SESSION['user_id']);
Copy after login

//2. Delete all session variables and clear the contents of the session file on the server

$_SESSION = [];
Copy after login

//3. Clear For all user sessions, delete the session files on the server

session_destroy();
Copy after login

//If you want to completely delete the session, the cookie corresponding to the PHPSESSID on the browser should also be deleted

//Execute , there can be no more setting statements in front, otherwise a PHPSESSID will be regenerated

setcookie('PHPSESSID', '', time()-3600);
Copy after login

//Summary: Correct and safe deletion of session should include the following three steps:

$_SESSION = [];  //清空当前用户的所有会话信息
session_destroy(); //清空当前域名下所有的会话信息
setcookie('PHPSESSID', '', time()-3600); //删除保存在客户端上的会话id
Copy after login

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template