Home  >  Article  >  Backend Development  >  Study Notes on Cookie and Session Application in PHP_PHP Tutorial

Study Notes on Cookie and Session Application in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:50:27780browse

The difference between cookie and session in PHP is that the cookie data is stored on the client side, while the session data is stored on the server side. Naturally, there will be some details in the usage method, but the latter is much safer than the former.

1. Introduction and differences of cookie&session

Cookie data is saved on the client side, and session data is saved on the server side.

To put it simply, when you log in to a website, if the web server uses session, then all data is stored on the server. Every time the client requests the server, it will send the sessionid of the current session to the server. Determine the corresponding user data flag based on the current sessionid to determine whether the user is logged in or has certain permissions. Since the data is stored on the server, you cannot forge it, but if you can obtain the sessionid of a logged-in user, you can also successfully forge the user's request using a special browser. The sessionid is randomly assigned when the server and client are connected. Generally speaking, there will be no duplication. However, if there are a large number of concurrent requests, the possibility of duplication is not impossible. I encountered it once. When I log in to a website, my own information is initially displayed. After a while, it times out, and when I refresh it, other people's information is actually displayed.

If the browser uses cookies, then all data is saved on the browser side. For example, after you log in, the server sets the cookie username (username). Then, when you request the server again, the browser will Send the username block to the server. These variables have certain special markers. The server will interpret it as a cookie variable. So as long as the browser is not closed, the cookie variable will always be valid, so it can be guaranteed not to be disconnected for a long time. If you can intercept a user's cookie variable and then forge a data packet and send it over, the server will still think you are legitimate. Therefore, the possibility of being attacked using cookies is relatively high. If the validity time is set, then it will save the cookie on the client's hard drive. The next time you visit the website, the browser will first check whether there is a cookie. If there is, it will read the cookie and then send it to server. If you save a forum cookie on your machine, the validity period is one year. If someone invades your machine, copies your cookie, and puts it in the directory of his browser, then when he logs in to the website, it will be Log in with your identity. So cookies can be forged. Of course, you need some ideas when forging. You can directly copy the cookie file to the cookie directory. The browser will not recognize it. It has an index.dat file that stores the creation time of the cookie file and whether it has been modified, so you must first have The cookie file of this website needs to be deceived by the browser in terms of guaranteed time. I once did an experiment on the school's vbb forum. I copied other people's cookies to log in and posted posts in someone else's name. There was no problem at all.

Session is a server-side storage space maintained by the application server. When the user connects to the server, a unique SessionID will be generated by the server, and the SessionID is used as the identifier to access the server-side Session storage space. The data of SessionID is saved to the client and saved with Cookie. When the user submits the page, the SessionID will be submitted to the server to access the Session data. This process does not require developer intervention. So once the client disables cookies, the Session will also become invalid.

The server can also pass the value of SessionID through URL rewriting, so it does not completely rely on Cookie. If client cookies are disabled, the server can automatically save the Session value by rewriting the URL, and this process is transparent to the programmer.

You can try it. Even if you don’t write cookies, the length of the cookie array taken out by request.getCookies(); is also 1, and the name of this cookie is JSESSIONID, and there is also a long binary string, which is SessionID. value.


2. Cookie configuration and application

Basic syntax: setcookie("cookie", "cookievalue", time()+3600, "/forum", ".xxx.com", 1);
Name Value Validity time, milliseconds Path Save domain Whether to use https

Accessing and handling cookies
Access basic syntax:

 代码如下 复制代码
echo $mycookie;
echo $cookiearray['0'];
echo $_COOKIE['mycookie'];   (推荐)
echo $HTTP_COOKIE_VARS['mycookie'];

Delete cookies
Remove basic syntax:

The code is as follows Copy code
setcookie("cookie",""); (Overwrite the original value with an empty cookie)
 代码如下 复制代码
setcookie("cookie","");   (用空cookie覆盖原值)
setcookie("cookie", "value", time()-1/time());   (时间销毁)
setcookie("cookie", "value", time()-1/time()); (time destruction)

Example:

The code is as follows Copy code
 代码如下 复制代码

if ($_POST['user'] && $_POST['password']) {
setcookie("us", $_POST['user']);
setcookie("pwd", $_POST['password']);
echo "用户:".$_COOKIE['us']."
"."密码:".$_COOKIE['pwd'];
}
?>


   用户:
  

   密码:
  

if ($_POST['user'] && $_POST['password']) {
setcookie("us", $_POST['user']);

setcookie("pwd", $_POST['password']);

echo "User:".$_COOKIE['us']."
"."Password:".$_COOKIE['pwd'];

}

?>

User:


Password:
 代码如下 复制代码
session_start();   //初始化,必须放在文件头。
$_SESSION['name'] = value;   //配置session。
echo $_SESSION['name'];   //使用session。
isset($_SESSION['name']);   //判断。
unset($_SESSION['name']);   //删除。
session_destroy();   //销毁所有session。
Note: The cookie must be operated before outputting, otherwise an error will occur. -------------------------------------------------- ---------- 1.session configuration and application Basic syntax:
The code is as follows Copy code
session_start(); //Initialization, must be placed in the file header. $_SESSION['name'] = value; //Configure session. echo $_SESSION['name']; //Use session. isset($_SESSION['name']); //Judge. unset($_SESSION['name']); //Delete. session_destroy(); //Destroy all sessions.

Give some examples to introduce the difference between session and cookie

<一>:session


Start session:


session_start();


PS: This function needs to be placed at the front of the file. There should be no output in front of it. It is best to write it at the top (without leading spaces).


​​​​​​​Set session:


                         $_SESSION['name']='value';


PS: When using it, directly use the $_SESSION[] method to set the value, where the "[ ]" part is the name of the session, and "=" is followed by the value.


Read session:


echo $_SESSION['name'];

PS: Whether setting session or reading session, you must first open the session (using session_start ()).

Destroy session:


1. Close the browser and automatically destroy.


2. Give $ _Session [] = ''; clear.

<二>:cookie


​​​​​​​Set cookies:


                           bool setcookie(string name[,string value[,int expire[,string path[,string domain[,bool secure[,bool httponly]]]]])

name: cookie variable name

                                                                                                                                        

expire: The time when the validity period ends,

Path: Valid directory,

domain: valid domain name, unique top-level domain

secure: If the value is 1, the cookie can only be valid on https connections. If it is the default value 0, both http and https are available.

For example:

setcookie('username','hello',time()+3600);

setcookie("username",'hello',time()+3600,"/~rasmus/",".paea.cn",1);

PS: Output data operation cannot occur before setcookie, otherwise an error similar to session_start() will occur.

Read cookie:

echo $_COOKIE['username'].'||';

echo $HTTP_COOKIE_VARS["username"];

PS: Two output methods.

Destroy cookies:


                                                       Set a time in the past to log out cookies

setcookie('username','hello',time()-3600);

PS: Output data operation cannot occur before setcookie, otherwise an error similar to session_start() will occur.

To summarize

Function:

Both sessions and cookies are used to temporarily record user data.

Difference:

1. SESSION is stored on the server side and cannot be modified by the user, which is relatively safe. COOKIE is stored on the client side and can be modified by the user, which is unsafe.

2.Session will be saved on the server for a certain period of time and will occupy server resources. Cookies are stored in the Temp directory under the user's windows.

3. The limit of a single cookie on the client is 4k

4. Use $_SESSION[] for session traversal and $_COOKIE[] for cookie traversal

5. The session cannot be used after disabling cookies

6. When using session, you must add session_start() and there must be no output in front.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632637.htmlTechArticleThe difference between cookie and session in php is that cookie data is saved on the client side, and session data is saved on the server side. Naturally, there will be some differences in details in how to use it, but the latter is better than the former...
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