The role of cookies and sessions

Summary of recent study of Session and Cookie, I found that many friends who do testing do not have a thorough understanding of this; if we understand the principles and uses of Cookie and session, it will be of great help in our testing work; especially in Interface testing and performance testing are in progress. . .

Directory

  • 1. Why use Cookie and Session?
  • 2. What are Cookies and Sessions?
  • 3. How to use Cookie and Session?
    • 1. Complete Cookie to complete the function of remembering user names:
      • ①The first scene:
      • ②The second scene:
      • ③The code is as follows:
    • 2. Complete the function of Session verification whether you have logged in
      • ①The first scene:
      • ②The second scene:
      • ③The code is as follows:
  • 4. The difference between Cookie and Session

1. Why use Cookie and Session?

Many times the client and server interact using the HTTP protocol, but the HTTP protocol is stateless; the request process of the HTTP protocol is based on TCP/IP. When the client requests the server, the server processes and responds. The process is stateless.

But sometimes it is necessary to save some client request information, identify certain client states, and intelligently and targetedly analyze the habits of certain clients. At these times, it is necessary to record the client's connection status, identify the status of the request, etc. So in order to solve similar things, you need to use Cookie and [Session](http://www.xprogrammer.com/906.html).

For example, the scenario of using cookies: some websites have the function of remembering user names. When you check this, the last logged-in user name will be saved the next time you enter the website; the scenario of using Seesion: use Seesion to verify Whether the user is logged in, use Session to save the verification code.

2. What are Cookies and Sessions?

(1) Cookie: When the client accesses an address, the request will be handed over to the server for processing. When sending the request, the browser will hand over the header information of the page to the server for processing. . During the processing, a cookie is generated on the server side. At the same time, some information that needs to be saved can be stored in this cookie. When generating a Cookie object, you need to determine the specific name and specific value. You can set the expiration time of the current [Cookie](http://www.xprogrammer.com/1226.html). After setting the expiration time, it is equivalent to persistence. If the data in the cookie is deleted, the cookie at this time will be saved on the client with the previous cookie name.

If the expiration time is not set, the lifetime of the current cookie is during the browser session. Once the browser is closed, the current cookie will no longer exist, and the cookie information at this time is stored in memory. On the server side, after processing, the generated Cookie will be added to the Http response header along with the Http response. After the browser receives the response, it will be processed on the client side according to the Cookie in the Http response header. Create Cookie. The next time the client makes a request, Http will be sent to the server along with the stored cookie. For a domain, all cookies created on the client can be shared, as long as the cookie has not expired.

(2) Session: Session is generated on the server side and stored on the server side, that is, in memory. The expiration time can be set for the generated Session. If the expiration time is not set, the default Session expiration time is 30 minutes (in different servers, its expiration time is slightly different. This article is based on Tomcat). However, the Session At the same time of generation, a SessionID associated with it will be generated. The storage of this SessionID requires Cookie to complete. SessionID is named JSESSIONID, and its value should be a string that is neither repeated nor easy to find patterns to imitate. The SessionID will be returned to the client along with this Http response and stored in the client. After the current request is issued again, the SessionID will be transmitted to the server along with the Http header, and the server will obtain the corresponding Session based on the current SessionID.

Among them: storing Session status through Cookie is just one of the ways. If cookies are disabled on the client, many websites can still store user information. One way to deal with this is URL rewriting, appending the SessionID directly to the request address. Another way to deal with it is to use the hidden automatic method. That is, the server automatically adds a hidden field to the form so that when the form is submitted, the SessionID is transmitted to the server for identification.

(3) To summarize: Cookies exist on the client side, such as in the local files of our computer (if the expiration time is set), in my local area (C:\Users\xxx\AppData\Roaming\Microsoft\ \Windows\Cookies):

You can also view it in your browser (chrome):

Session exists on the server side (my apche is also installed locally):

When sending a request, the cookie will automatically bring the Seesionid:

3. How to use Cookie and Session?

First of all, let me explain that the following is written in PHP. The reason for writing this process is to deepen the understanding of Cookie and Session. It is not abstract to just look at the theory.

1. Complete Cookie to complete the function of remembering user names:

①The first scene:

Enter the username and choose to save the username –> Submit –> Print and set the cookie successfully –> Return to the login page –> The username will be filled in automatically (as long as you visit the login page, within the cookie validity period)

The cookies set here can be viewed in the browser:

The name is userName, the value is: xiaoshitou, the storage time is: 1 hour

②The second scene:

Enter the user name, do not choose to save the user name –> Submit –> Print the cookie deletion successfully –> Return to the login page –> The value of the user name is empty (the set cookies will be cleared)

③The code is as follows:

(Two files: saveUserNameView.php, saveUserNameProcess.php):

saveUserNameView.php: (code for login page)

1 <?php
 2 /**
 3 * Created by PhpStorm.
 4 * User: LSH
 5 * Date: 2016/11/25
 6 * Time: 11:12
 7 */
 8?>
 9 <html>
10 <head>
11 <meta charset="utf-8">
12 <title>Save username</title>
13 </head>
14 <body>
15 <h1>Login page</h1>
16 <form action="saveUserNameProcess.php" method="post">
17 <table>
18 <tr><td>Username</td><td>
19 <input type="text" name="userName" value="<?php if (!empty($_COOKIE['userName'])){echo $_COOKIE['userName' ];} ?>"></td></tr>
20 <tr><td>Password & amp;nbspcode</td><td><input type="password" name="password"></td></tr>
21 <tr><td colspan="2"><input type="checkbox" name="saveUserName" value="saveUserName">Save user name</td></tr>
22 <tr><td colspan="2"><input type="submit" name="submit" value="submit"></td></tr>
23 </table>
24 </form>
25 </body>
26 </html>

saveUserNameProcess.php: (code for processing logic, saving cookies, deleting cookies)

1 <?php
 2 /**
 3 * Created by PhpStorm.
 4 * User: LSH
 5 * Date: 2016/11/25
 6 * Time: 11:12
 7 */
 8 
 9 # Get post submission information
10 // Get username
11 if (!empty($_POST['userName'])){<!-- -->
12 $userName = $_POST['userName'];
13}
14 // Get password
15 if (!empty($_POST['password'])){<!-- -->
16 $password = $_POST['password'];
17}
18 // Get whether to choose to save the user name
19 if (!empty($_POST['saveUserName'])){<!-- -->
20 // When checked, save the cookie
21 $saveUserName = $_POST['saveUserName'];
22 // Save Cookie
23 // userName: the cookie name set
24 // $userName: Username submitted by the user
25 // time() + 60*60: counting from the current time, 60*60 seconds; that is, the time for saving the cookie, the cookie expires after 1 hour
26 setcookie('userName',$userName,time() + 60*60);
27 echo "<br>Set Cookie Success!<br>";
28 }else{<!-- -->
29 // When the user does not choose to save the user
30 // Deleting a cookie means clearing the cookie value and setting the cookie to expire.
31 setcookie('userName','',time()-200);
32 echo "<br>Delete Cookie Success!<br>";
33}
34 // Return to login page
35 echo "<a href='saveUserNameView.php'>Return to login page</a>";

2. Complete the function of Session verification whether you have logged in

①The first scene:

Enter username and password –> Submit –> Verification successful –> Enter the management page

Login.php (login page)->loginProcess.php (processing login logic page)->admin.php (administration page)

Login verification is successful: loginProcess.php will save the user name in the session and set a cookie to the client:

The server will also report an error in a session file, the content of which is admin:

When jumping to admin.php, the sessionid will be brought into the cookie and sent to the server:

②The second scene:

Users directly access the admin.php management page –> jump directly to the login page (because this is illegal and must be logged in successfully before accessing)

When accessing the admin.php page directly, the login login.php will be redirected to control it. Only users who have successfully logged in can access this page.

③The code is as follows:

Login.php (login page)->loginProcess.php (processing login logic page)->admin.php (administration page)

login.php (login page):

1 <?php
 2 /**
 3 * Created by PhpStorm.
 4 * User: LSH
 5 * Date: 2016/11/25
 6 * Time: 14:35
 7 */
 8?>
 9 <html>
10 <head>
11 <meta charset="utf-8">
12 <title>Save username</title>
13 </head>
14 <body>
15 <h1>Login page</h1>
16 <form action="loginProcess.php" method="post">
17 <table>
18 <tr><td>Username</td><td><input type="text" name="userName"></td></tr>
19 <tr><td>Password & amp;nbspcode</td><td><input type="password" name="password"></td></tr>
20 <tr><td colspan="2"><input type="submit" name="submit" value="submit"></td></tr>
21 </table>
22 </form>
23 </body>
24 </html>

loginProcess.php (determine whether the username is correct and set the session)

1 <?php
 2 /**
 3 * Created by PhpStorm.
 4 * User: LSH
 5 * Date: 2016/11/25
 6 * Time: 14:41
 7 */
 8 # Get the information submitted by post
 9 // Get username
10 if (!empty($_POST['userName'])){<!-- -->
11 $userName = $_POST['userName'];
12}
13 // Get password
14 if (!empty($_POST['password'])){<!-- -->
15 $password = $_POST['password'];
16}
17
18 if ($userName == 'admin' & amp; & amp; $password == '123456'){<!-- -->
19 //Username: admin; Password: 123456
20 // Log in successfully, jump to the management page: admin.php
21 header("Location: admin.php");
22 //Set session
23 session_start();
24 $_SESSION['userName'] = $userName;
25 }else{<!-- -->
26 // When the username and password are incorrect, return to the login page
27 header("Location: login.php");
28 }

admin.php (verify whether the user is logged in based on the session, jump to the login page if not logged in, and log in)

1 <?php
 2 /**
 3 * Created by PhpStorm.
 4 * User: LSH
 5 * Date: 2016/11/25
 6 * Time: 14:37
 7 */
 8 // Get userName in Session
 9 session_start();
10 if (!empty($_SESSION['userName'])){<!-- -->
11 // When userName has a value, print welcome. Since the management page
12 echo $_SESSION['userName'].",welcome to my system!";
13 echo "<h1>Management Page</h1>";
14 }else{<!-- -->
15 // When $_SESSION['userName'] is empty, it means that the user illegally accesses the management page.
16 // Jump to the login page
17 header("Location: login.php");
18}

4. The difference between Cookie and Session

1. Cookie exists on the client and Session exists on the server.

2. Use Session if security requirements are high, and Cookie if security requirements are low.

3. Cookie can only store strings, and Session can store any information.

4. If the cookie does not set a time, the cookie will become invalid when the browser is closed and will not be saved locally; the life cycle of the Session is a session (from when the browser is started to when the browser is closed)

5. When storing relatively persistent information, you should consider using cookies, because cookies can be stored on the client in the form of files. Session can be used when performing some login verification and information interception.