Cookies and sessions in PHP
In PHP, there are two very important functions, which are our cookie and session. So how are they used and what is the difference?
This article will take you to understand cookies and sessions
Introduction to cookies
Cookies are data stored in the client browser. We use cookies to track and store User data. Typically, cookies are returned from the server to the client via HTTP headers. Most web programs support Cookie operations.
Because Cookies exist in the HTTP header, they must be set before other information is output, similar to the usage restrictions of the header function.
Set cookie method
setcookie("name",'zhangsan');
setcookie("name",'zhangsan',time()+60);/ /Set the cookie validity time to 60 seconds
//setcookie("visittime",date("y-m-d H:i:s"),time()+60);//Set the variable that saves the cookie expiration time
Read cookie method
$name=$_COOKIE["name"};
Delete cookie method
setcookie("name","" ,time()-1);//Set the time of cookie() to the current time minus 1. The time() function returns the current timestamp expressed in seconds. Subtracting 1 second from the expiration time will get the past time, so Delete cookie
To delete cookiez, you only need to set the second parameter in the setcookie() function to a null value, and set the expiration time of the third parameter cookie to be less than the current time of the system
After understanding cookies, let’s take a look at session
session stores the user’s session data on the server, with no size limit, through a session_id is used for user identification. By default, PHP session id is saved through cookies, so to some extent, seesion relies on cookies. But this is not absolute. The session id can also be implemented through parameters. As long as the session id can be passed to the server for identification, the session can be used.
Using session
Using session in PHP is very simple. First execute the session_start method to open the session, and then read and write the session through the global variable $_SESSION.
session_start();$_SESSION['test'] = time();var_dump($_SESSION);
session will automatically encode and decode the value to be set, so session Can support any data type, including data and objects.
session_start();$_SESSION['ary'] = array('name' => 'jobs');$_SESSION['obj'] = new stdClass();var_dump($_SESSION);
By default, sessions are stored on the server in the form of files. Therefore, when a session is opened on a page, the session file will be exclusively occupied. This will cause other concurrent accesses of the current user to be unable to execute and wait. This problem can be solved by using cache or database storage, which we will talk about in some advanced courses.
Delete and destroy session
To delete a session value, you can use PHP's unset function. After deletion, it will be removed from the global variable $_SESSION and cannot be accessed.
session_start();$_SESSION['name'] = 'jobs';unset($_SESSION['name']);echo $_SESSION['name']; //Prompt name does not exist
If you want to delete all sessions, you can use the session_destroy function to destroy the current session. session_destroy will delete all data, but the session_id still exists.
session_start();$_SESSION['name'] = 'jobs';$_SESSION['time'] = time();session_destroy();
It is worth noting that session_destroy The value in the global variable $_SESSION will not be destroyed immediately. Only when it is accessed next time, $_SESSION will be empty. Therefore, if you need to destroy $_SESSION immediately, you can use the unset function.
session_start();$_SESSION['name'] = 'jobs';$_SESSION['time'] = time();unset($_SESSION);session_destroy(); var_dump($_SESSION); //It is empty at this time
If you need to destroy the session_id in the cookie at the same time, which may usually be used when the user logs out, you also need to explicitly call the setcookie method to delete the cookie value of session_id.
Use session to store user login information
Session can be used to store many types of data, so it has many uses. It is often used to store user login information, shopping cart data, or Some temporary data for temporary use, etc.
After the user successfully logs in, the user's information can usually be stored in the session. Generally, some important fields will be stored separately, and then all user information will be stored independently.
$_SESSION['uid'] = $userinfo['uid'];$_SESSION['userinfo'] = $userinfo;
Generally speaking, login information can be stored in sessioin , or can be stored in cookies. The difference between them is that session can easily access multiple data types, while cookies only support string types. At the same time, for some data with higher security, cookies need to be formatted and Encrypted storage, and session storage on the server side is more secure.
header("content-type:text/html; charset=utf-8");
session_start();//Assume that the user logs in successfully and obtains the following user data $userinfo = array(
'uid' => 100,
'name' => 'liu',
'email' => '123456789@qq.com',
'sex' => 'man',
'age' => '23');
/* Save user information to session*/
$_SESSION['uid'] = $userinfo['uid'];
$_SESSION['name'] = $userinfo['name'];
$_SESSION ['userinfo'] = $userinfo;
//* A simple way to save user data to cookies*/
$secureKey = 'php';
//Encryption key $str = serialize($userinfo);
//Serialize user information //Before encrypting user information
$str = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5( $secureKey), $str, MCRYPT_MODE_ECB));
//After encrypting user information//Storing the encrypted user data into cookies
setcookie('userinfo', $str) ;
?>
Finally, let’s take a look at the biggest difference between session and cookie:
First, session is session The information is stored on the server, and the client's information is transmitted through a session ID. At the same time, after the server receives the session ID, it provides relevant session information resources based on this ID.
Secondly, the cookie combines all the information with The form of text is saved on the client and managed and maintained by the browser
3. Since the session is stored on the server, all remote users cannot modify the content of the session file, and the cookie
is a client End storage, all sessions are much more secure than cookies, and of course there are many advantages, such as easy control, customizable storage, etc. (stored in the database)...

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
