Home  >  Article  >  How to use session in php

How to use session in php

无忌哥哥
无忌哥哥Original
2018-06-28 11:15:153804browse

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();

//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;

//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'];

//Update

$_SESSION['user_name'] = 'peter';
echo $_SESSION['user_name'];

//Delete

//1. Delete a single session variable

unset($_SESSION['user_id']);

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

$_SESSION = [];

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

session_destroy();

//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);

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

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

Statement:
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
Previous article:How to use cookies in phpNext article:How to use cookies in php