HTTP protocol features:
Stateless, no correlation between multiple requests
That is, the same user requests different pages of the same website, the server can not identify whether the request is initiated by the same user. Therefore, users cannot perform continuous business logic.
For example: login, already logged in on page A, request page B, prompt not logged in.
cookie and session distinguish:
-
cookie: A container for storing data on the browser side
-
session is a container for storing data on the server side
1. cookie
-
A container for storing data on the browser side
-
Cookies can be manipulated using js
-
Cookies allow server scripts (PHP scripts) to store data on the browser side
-
Cookie features: after data setting in cookie, when the browser requests the server to specify the page again, it will automatically carry the data in cookie to the server, and the data in cookie can be obtained in the server.
Browsers view cookie data
js operation cookie (understand)
// Setting cookie s document.cookie = 'name=zs'; document.cookie = 'pwd=123'; // Get the value in the cookie document.cookie;
jquery.cookie.js plug-in operates cookie
// Introduce the plug-in js file to the page, based on jquery cookie('weight',100,{expires:7}); // Set expires expiration time $. cookie('name'); // get removeCookie('name'); //delete Cookie (key, value, {expires: expired days}) $. cookie (key) / / get
PHP operates cookies (server-side operates cookies)
//Setting cookie s setcookie('Name','value'); setcookie('Name','value','Term of validity'); //Delete cookie s and set the expiration time to the previous time setcookie('Name','',time()-1000); //Getting cookie s //The $_COOKIE is PHP's super-global variable, which stores cookie data from browsers. The $_COOKIE can only be used to obtain data. $_COOKIE['Name'];
Note:
-
Data in cookie s can be shared by pages of the same website
-
Cookies in different browsers cannot be shared
-
The cookie data is stored in the browser and sent to the server with the cookie data in the request message every time the server requests it.
-
The server side can not directly operate cookies. It informs the browser to set cookies by setting a response head on the server side.
-
The data validity period in cookie is not set to session level, browser closes, session ends, data destruction
-
cookie storage capacity is small, about 4 KB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> // cookie: Browser-side storage space // To manipulate cookie s by native (understand) // 1. Settings requiring key-value pairs, separated by = // document.cookie = "name=pengpeng"; // document.cookie = "age=18"; // document.cookie = "desc=shuai"; // 2. Obtain, document.cookie obtains all cookies at once and returns them as strings // Separation by ";", name=pengpeng; age=18; desc=shuai // console.log( document.cookie ); // Getting through js is cumbersome (practicing native) // Function: Extract the desired cookie value from document.cookie // name=pengpeng; age=18; desc=shuai // Requirements: Pass age, return 18, pass desc, return shuai function getValue( key ) { var str = document.cookie; // name=pengpeng; age=18; desc=shuai var arr = str.split("; "); // ["name=pengpeng", "age=18", "desc=shuai"] for ( var i = 0; i < arr.length; i++ ) { var k = arr[i].split("=")[0]; // name var v = arr[i].split("=")[1]; // pengpeng if ( key === k ) { // Traverse, return the value if the key passed in is equal to the key at the time of traversal return v; } } } console.log( getValue( "age" ) ); </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script src="./jquery-1.12.2.js"></script> <script src="./jquery.cookie.js"></script> <script> // Cookies can be shared across multiple pages // Through plug-ins, jquery.cookie.js can help us operate cookies // 1. Set cookie: $. cookie (key, value) $.cookie( "name", "dapp" ); $.cookie("age", 18); // 2. Get: $. cookie(key) console.log( $.cookie( "name" ) ); // 3. Delete: $. removeCookie (key) $.removeCookie( "age" ); // 4. Expiration time. If no expiration time is set, the default cookie is session level. Close the browser and it will be destroyed. $.cookie( key, value, { expires: Days of expiration } ); $.cookie( "name", "pengpeng" ); $.cookie( "name", "pengpeng", { expires: 7 }); </script> </body> </html>
<?php // Note: Spaces, equals, semicolons, stored cookie values should not appear above special characters // 1. Setting cookie s setcookie(key, value); setcookie( "desc", "hello_kitty" ); // 2. Acquisition // The $_COOKIE superglobal variable can be used to obtain all cookie information // Returns an associative array echo '<pre>'; print_r( $_COOKIE ); echo '</pre>'; echo $_COOKIE['desc']; // 3. Set cookie expiration time // Setcookie (key, value, timestamp (when it expires, starting in 1970 seconds) setcookie( "name", "pengpeng", time() + 7*24*3600 ); // 4. If the cookie is set to the past time, it will be deleted and destroyed. setcookie( "name", "ppp", time() - 1 ); // setcookie( "name", "pp" ); // The browser carries the data in the cookie every time it requests it echo '<pre>'; print_r( $_COOKIE ); echo '</pre>'; // The server can't directly manipulate cookie s, but it can set the response header // In the response header, Set-Cookie: name=ppp // In the future, the browser will receive requests, view response headers, and automatically set cookies on the browser side according to set-cookie // setcookie( "name", "ppp" ); // Consideration questions: // 1. The storage capacity of cookies is 4k // 2. Can cookie s be shared on the same website? // 3. cookie is a container for storing data in browsers. Why can servers get data in cookies? // Because cookies, when requested, carry data from cookies in the request header // The server can read the content of the request header and indirectly get the data in the cookie. // 4. Cookies are the container for storing data in browsers. Why can servers set data in cookie s? // setcookie sets the response header, set-cookie: name=pp // Notify the browser to set cookie s in the future ?>
2. session
-
A container for storing data on the server side
-
The session container is an array of values and settings through the superglobal variable $_SESSION
-
Before session can be used, session_start must be used to open the session mechanism.
-
The data in session can be shared by the current website
Basic operation of session
Open session mechanism (this method must be invoked before using session)
session_start(); //Open session sessions or reuse sessions that have been created.
Note:
-
A session ID is generated randomly for each first-time user in the server.
-
Then, according to session ID, we automatically create a session session session file, in which we can store the user's data.
-
When responding, set-cookie is set in the response header to store the user's session ID.
-
In the future, the browser will store session Id in the cookie according to the response header and carry it on the next request.
Next time we visit, the server will find the session file of the user according to session Id. We can read the user information from session and keep the session.
Set and get the data in the session (operated by the superglobal variable $_SESSION):
//Set up $_SESSION['key']='value'; //delete unset($_SESSION['key']); //Clear session $_SESSION=[]; //Delete session session file directly, PHP script will not be able to read session data session_destroy(); //Get the id of the session session_id();
<?php // 1. session server-side container for storing data // 2. session can be shared on multiple pages on the server side // The $_SESSION superglobal variable is an associative array // session data of the current requesting user can be obtained through $_session // Each user has its own session space // Open session mechanism session_start(); // echo '<pre>'; // print_r( $_SESSION ); // echo '</pre>'; // // 1. Storage $_SESSION['name'] = 123; $_SESSION['age'] = 18; // // 2. Modification $_SESSION['name'] = 456; // // 3. Acquisition echo $_SESSION['name']; // // 4. Delete unset($_SESSION['age']); echo '<pre>'; print_r( $_SESSION ); echo '</pre>'; ?>
<?php // Clear the user's login status for the first time // 1. Clean out cookie s // 2. Delete session files on the server side // session_start(); // After the session mechanism is started // 1. If the current user visits the server for the first time, a session ID (random string) is automatically generated. // echo session_id(); // 2. According to the generated session id, the server will open a session storage space for the user. // Create a new session file. The name of the session file is session id, which can be used to store data. // $_SESSION['name'] = 'pengpeng'; // 3. Pass session ID back to the browser. // Set-Cookie: PHPSESSID=e54nnd2r7ohgulbm7moq5pb736; // Setting session ID in cookie s in the future // 4. Browser-side parses the response header and sets session Id to cookie // 5. On the second visit, the data stored in the cookie will be carried when requested, and session Id will be carried. // 6. The back server can find the corresponding session file according to sessionId and recognize the user. ?>
3. Application of COOKE and SESSION - Maintaining login status
The basic idea of login module:
-
If the user logs in successfully, record the user's login status in the server
-
session_start(), which automatically generates session Id and creates session files for first-time users.
-
We need to record the current user's information in the session file
-
Set session ID for browser cookie s by response header
-
-
Follow-up visits to other pages (personal centers), browsers automatically send session IDs stored in cookie s to servers
-
Server will browser to pass according to session ID, find the corresponding session file, see if there is the current user's information stored in it.
-
Yes: The user has logged in and browsed normally.
-
No: User is not logged in, jump to login page
-
if($name=='zs'&&$pwd=='666'){ // Log in successfully and store the user's unique identity in session // The id of the user database is 1 $id = 1; session_start(); $_SESSION['userid']=$id; }
session_start(); if(!empty($_SESSION['userid'])){ //Normal browsing }else{ header('location:./04-login.html'); die();//Later code does not execute }