Differences between cookie and session in PHP instance analysis, cookie instance Analysis _ PHP Tutorial

Source: Internet
Author: User
Tags http cookie php session php print set cookie
Differences between cookie and session in PHP: instance analysis and cookie instance analysis. Differences between cookies and sessions in PHP instance analysis. cookie instance analysis cookies and sessions are very important skills in PHP programming. A deep understanding of cookie and session applications is used to analyze the differences between cookies and sessions in PHP, and analyze cookie instances.

Cookie and session are very important techniques in PHP programming. An in-depth understanding of cookie and session applications is the basis for PHP programming. This article analyzes the differences between the two in the form of instances. The specific analysis is as follows:

1. Cookie
Cookie is a mechanism for storing data in a remote browser and tracking and identifying users.
PHP sends cookies in the http header. Therefore, the setcookie () function must be called before other information is output to the browser, which is similar to the header () function.

1.1 Set cookie:
You can use the setcookie () or setrawcookie () function to set the cookie. You can also set it by sending an http header directly to the client.

1.1.1 Use the setcookie () function to set the cookie:

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

Name: cookie variable name
Value: The value of the cookie variable.
Expire: the end time of the validity period,
Path: valid directory,
Domain: valid domain name, unique in top-level domain
Secure: if the value is 1, the cookie can only be valid for https connections. if the default value is 0, both http and https can be used.
Example:

<? Php $ value = 'something from somewhere'; setcookie ("TestCookie", $ value);/* simple cookie setting */setcookie ("TestCookie", $ value, time () + 3600);/* valid for 1 hour */setcookie ("TestCookie", $ value, time () + 3600 ,"/~ Rasmus/"," .example.com ", 1);/* valid directory /~ Rasmus, valid domain name example.com and all its subdomains */?>

Set multiple cookie variables: setcookie ('Var [a] ', 'value'); use an array to represent variables, but its subscript is not enclosed in quotation marks. in this way, you can use $ _ COOKIE ['var'] ['A'] to read the COOKIE variable.

1.1.2. use header () to set the cookie;

header("Set-Cookie: name=$value[;path=$path[;domain=xxx.com[;...]]");

The following parameters are the same as those listed in the setcookie function above.
For example:

$value = 'something from somewhere';header("Set-Cookie:name=$value");

1.2 Cookie reading:
Directly use php's built-in Super global variable $ _ COOKIE to read the cookie on the browser.
The cookie "TestCookie" is set in the preceding example. now we can read:

print $_COOKIE['TestCookie'];

Is the COOKIE output ?!

1.3 Delete a cookie
Set the effective time to less than the current time, and set the value to null. for example:

setcookie("name","",time()-1);

Similar to header.

1.4 Troubleshooting:

1) an error message is prompted when setcookie () is used, probably because there is an output or space before setcookie () is called. it is also possible that your document is converted from other character sets. the document may be followed by a BOM signature (that is, add some hidden BOM characters to the file content ). the solution is to prevent this problem in your document. you can also use the ob_start () function to handle this problem.

2) $ _ COOKIE is affected by magic_quotes_gpc and may be automatically escaped

3) it is necessary to test whether the user supports cookies.

1.5 cookie working mechanism:
Some learners are impulsive and have no idea about the principle, so I put it behind me.
A) the server sends an http Set-Cookie header in response and sets a cookie in the client (multiple cookies require multiple heads ).
B) the client automatically sends an http cookie header to the server, and the server receives and reads the cookie.

HTTP/1.x 200 OKX-Powered-By: PHP/5.2.1Set-Cookie: TestCookie=something from somewhere; path=/Expires: Thu, 19 Nov 2007 18:52:00 GMTCache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0Pragma: no-cacheContent-type: text/html

This line implements the cookie function. after receiving this line
Set-Cookie: TestCookie = something from somewhere; path =/
The browser will create a cookie file on the disk of the client, and write:
TestCookie = something from somewhere;

This line is the result of using setcookie ('testcookie ', 'Something from somewhere. that is, the result of using header ('set-Cookie: TestCookie = something from somewhere; path =.

2. Session
The session uses a cookie with the expiration time set to 0, and uses a unique identifier (a long string) called the session ID ), generate some session files synchronously on the server (you can define the session storage type by yourself) and associate them with the user machine. web applications store data related to these sessions, and transmit data between pages as users.
Visitors to the website will be assigned a unique identifier, the so-called session ID. It is either a cookie stored on the client or transmitted through a URL.
Session support allows users to register any number of variables and keep them for use by each request. When visitors visit the website, PHP will automatically (if session. auto_start is set to 1) or when a user request (explicitly called by session_start () or secretly called by session_register () checks whether a specific session ID is sent in the request. If yes, the previously saved environment is rebuilt.

2.1 Transfer of sessionID

2.1.1 send sessin ID through cookie

Use session_start () to call the session. when the server generates the session file, it generates the session ID hash value and the session name with the default value PHPSESSID, and sends the variable (default) to the client) PHPSESSID (session name), with a 128-bit hash value. the server will use this cookie to interact with the client.

The session variable value is serialized in php and stored in a text file on the server. it interacts with the coolie whose client variable name is PHPSESSID by default.

That is, the server automatically sends the http header:

header('Set-Cookie: session_name()=session_id(); path=/');

That is

setcookie(session_name(),session_id());

After you jump to a new page from this page and call session_start (), PHP checks the session data stored on the server that is associated with the given ID. If no session data is found, a new dataset is created.

2.1.2 send session ID through URL

This method is used only when the user disallows the use of cookies, because the browser cookie is already used. this method is not required for security purposes.

=<?php print session_id() ?>">xxx,

You can also pass the session value through POST.

2.2 Basic session usage example

<? Php // page1.phpsession _ start (); echo 'Welcome to page #1 '; /* Create a session variable and assign a value to the session variable */$ _ SESSION ['favcolor'] = 'green'; $ _ SESSION ['Animal '] = 'cat '; $ _ SESSION ['Time'] = time (); // if the client uses cookies, the session can be directly transferred to page2.phpecho'
Page 2'; // if the client disables cookieecho'
Page 2';/* in php5.2.1 by default, SID only has a value when the cookie is written. if the cookie corresponding to the session already exists, the SID will be (undefined) null */?>

<? Php // page2.phpsession _ start (); print $ _ SESSION ['Animal ']; // print a single sessionvar_dump ($ _ SESSION ); // Print the session value passed by page1.php?>

2.3 use the session function to control page cache.

In many cases, we need to determine whether our webpage is cached on the client or set the cache validity period. for example, we need to log on to the webpage to view some sensitive content, if the cache is cached locally, you can directly open the local cache to browse the webpage without logging on.

Use session_cache_limiter ('private'); to control the page client cache, which must be called before session_start.
Use session_cache_expire (int) to control the client cache time; unit (s). it must also be called before session_start.
This is only a method for controlling the cache when session is used. we can also control the page cache in header.

2.4 delete a session
Three steps are required.

<? Phpsession_destroy (); // Step 1: delete the session file on the server, which uses setcookie (session_name (), '', time ()-3600); // Step 2: delete the actual session: $ _ SESSION = array (); // Step 3: delete the $ _ SESSION global variable array?>

2.5 session usage in PHP large-scale web applications

The default session storage method is not suitable for websites with large traffic volumes. Currently, the optimal method is to access sessions using databases. at this time, the function bool session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, callback gc) is the solution to solve this problem.
The function uses the following six functions:
1. bool open () is used to open the session storage mechanism,
2. bool close () closes the session storage operation.
3. this function is used when mixde read () is installed in session data from the storage.
4. bool write () writes all data of the given session ID to the storage.
5. bool destroy () destroys the data associated with the specified session ID
6. bool gc () garbage collection of data in the storage system
For example, see the session_set_save_handler () function in the php Manual.
If the class is used for processing, use

session_set_save_handler(  array('className','open'),  array('className','close'),  array('className','read'),  array('className','write'),  array('className','destroy'),  array('className','gc'),)

Call the six static methods in the className class. you do not need to call static methods if you can change the object, but do not need to generate objects if you use static members. This provides better performance.

2.6 Common session functions:
Bool session_start (void); initialize the session
Bool session_destroy (void): deletes the session associated files on the server.
String session_id () id of the current session
String session_name () indicates the name of the session currently accessed, that is, the cookie name used by the client to save the session ID. PHPSESSID is used by default.
Array session_get_cookie_params () details of the session associated with this session.
String session_cache_limiter () controls the client cache of pages using Sessions
Ini session_cache_expire () controls the client cache time
Bool session_destroy () deletes the file on the server that stores session information.
Void session_set_cookie_params (int lifetime [, string path [, string domain [, bool secure [, bool httponly]) sets session details associated with this session
Bool session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, callback gc) defines the function for processing sessions (not by default)
Bool session_regenerate_id ([bool delete_old_session]) allocates a new session id

2.7 session security problems

By investing a lot of energy, attackers try to obtain valid session IDs of existing users. with session IDs, they may be able to have the same capabilities as this users in the system.
Therefore, our main solution is to verify the validity of the session ID.

<? Phpif (! Isset ($ _ SESSION ['User _ agent']) {$ _ SESSION ['User _ agent'] = $ _ SERVER ['remote _ ADDR ']. $ _ SERVER ['http _ USER_AGENT '];}/* if the user session ID is forged */elseif ($ _ SESSION ['User _ agent']! = $ _ SERVER ['remote _ ADDR ']. $ _ SERVER ['http _ USER_AGENT']) {session_regenerate_id () ;}?>

2.8 Differences between Session passing through cookies and passing through SID:

Under the default configuration of the session in php5.2.1, when a session is generated, the server generates a pre-defined Super global variable SID while sending the header set-cookie (that is, writing a cookie is equivalent to throwing a SID .), when $ _ COOKIE ['phpsessid '] exists, no cookie is written or the Super global variable SID is generated. at this time, the SID is empty.

2.9 session instance

<? Php/*** verify the validity of the session **/function sessionVerify () {if (! Isset ($ _ SESSION ['User _ agent']) {$ _ SESSION ['User _ agent'] = MD5 ($ _ SERVER ['remote _ ADDR ']. $ _ SERVER ['http _ USER_AGENT ']);}/* if the user session ID is forged, the session ID */elseif ($ _ SESSION ['User _ agent']! = MD5 ($ _ SERVER ['remote _ ADDR ']. $ _ SERVER ['http _ USER_AGENT ']) {session_regenerate_id () ;}/ *** destroy session ** three steps are perfectly implemented. do not miss **/function sessionDestroy () {session_destroy (); setcookie (session_name (), '', time ()-3600); $ _ SESSION = array () ;}?>

Note: The reason why the session header has been sent is the same as that of cookie.
In php5, the registry configuration options of all php sessions are configurable during programming. In general, we do not need to modify the configuration. for more information about php session registry configuration options, see Session session processing functions in the manual.

I believe this article provides some reference for you to better understand the usage of cookies and sessions in PHP.


What is the difference between php session and cookie? Is there a specific example?

Session is a temporary user data saved by a server of the Web service stateless session. Based on this data, the server can reconstruct the user session information.
Cookies are used to store temporary data of local scripts and maintain session authentication during interaction with the server.

To put it simply, the session needs to enable cookie for normal use.
When an HTTP packet is captured, the COOKIE: PHPSESSID = xxxx is sent when the webpage content is requested, and the returned header contains SET-COOKIE: PHPSESSID = xxxx. If the Cookie value is changed in the header information, the logon status of your user will change, because the server cannot find the corresponding session file based on the PHPSESSID value.

If you leave the server side and only consider the initial HTML + script method, there is no session file at all, because it is a static page, no subsequent relationship with the server (aside from ajax requests ). Therefore, the cookie becomes a local storage file for scripts. The cookie format is "key name = key value", separated.

Duration difference:
The cookie has a defined duration. if the duration is exceeded, the browser determines that it has expired, and then discards the cookie file and deletes it. Therefore, even if the Session on the server still exists, because the cookie information is lost, the corresponding PHPSESSID value cannot be retrieved and the Session reconstruction cannot be implemented. If the period is not long, the browser will automatically expire when it is closed.
You can specify the validity period of a session. if a Session with the PHPSESSID value in this COOKIE has been requested, the session length will be automatically extended, after the request has not been sent for a long time, it will be cleared through the recycle mechanism, but it is not completely guaranteed that it can be recycled normally. If the Session file corresponding to PHPSESSID does not exist even if the cookie file still exists locally after the Session is recycled, the Session cannot be rebuilt.

(Php) session and cookie are different

Session stores cookies on servers and clients.
Yes, the biggest difference between Session and Cookie is that the following is what I have organized based on code and related understanding.
Code:
A1.php
Function CookiesTest ($ newValue ){
If (! Isset ($ _ COOKIE ["CookiesTest"]) {
Setcookie ('cookiestest ', $ newValue, time () + 3600 );
Echo "CookieValue:". $ _ COOKIE ["CookieValue"];
}
}
Function SessionTest ($ newValue ){
If (! Session_is_registered ('sessiontest ')){
Session_register ("SessionTest ");
}
}
CookiesTest ("HelloCookies! ");
SessionTest ("HelloSession! ");
Echo "CookieValue:". print_r ($ _ COOKIE )."
";
Echo "CookieValue:". $ _ COOKIE ["CookiesTest"]."
";
$ SessionTest = "dd ";
Echo $ SessionTest;
Echo $ _ SESSION ["SessionTest"];
?>

A2.php

// Session_start ();
Echo $ _ SESSION ["SessionTest"];
Echo $ CookiesTest;
?>
Cookie:
(1) used to store the data used to access a page consecutively. (That is, the local Cookie value is not a global change concept in the true sense, that is, for A1.php, the corresponding COOKIE value can be called by adjusting $ _ Cookie ["XX, however, if you open an A2.php Internet Explorer and then retrieve the Cookie value, you will not be able to retrieve it! Therefore, cookies are not actually a global concept .)
(2) cookies are stored on the client and stored in the Temp directory of user WIN.

Session: (a special Cookie. The Session will also be disabled when the Cookie is disabled, but the Session can be re-obtained through redirection)
(1) it can be used to store the globally unique variables of users. For a Session, you can use Session_start () to redirect the Session and obtain the value of the Session, and perform operations without interrupting whether the Session is opened repeatedly. The above A1.php performs the Session operation. if another IE is opened and Sessoin_start () is used; then the corresponding Session variables will be re-enabled... the remaining full text>

Cookie and session are very important techniques in PHP programming. In-depth understanding and understanding of cookie and session applications...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.