The similarities and differences between cookies and sessions in PHP and their use

Source: Internet
Author: User
Tags session id setcookie


The similarities and differences between the cookie and session:


First. Cookie mechanism



Cookies are small pieces of text that the server stores on the local machine and are sent to the same server with each request. The IETF RFC 2965 HTTP State Management mechanism is a generic cookie specification. The Web server sends cookies to the client using HTTP headers, and in the client terminal, the browser parses the cookies and saves them as a local file, which automatically binds any requests from the same server to these cookies.



Specifically, the cookie mechanism uses a scheme that maintains state on the client. It is the storage mechanism of session state on the client side, and he needs the user to open the cookie support of the clients. The purpose of cookies is to resolve the problem of stateless defects in the HTTP protocol.
Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header. However, purely client-side scripts such as JavaScript can also generate cookies. And the use of cookies by the browser in accordance with certain principles in the background automatically sent to the server. The browser checks all stored cookies and, if a cookie declares a scope greater than or equal to the location of the resource to be requested, sends the cookie to the server on the HTTP request header of the requesting resource.



The contents of the cookie mainly include: name, value, expiration time, path and domain . The path together with the domain constitutes the scope of the cookie. If you do not set an expiration time, the cookie will be closed for the duration of the browser session. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and the cookies remain valid until the set expiration time expires. Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them.



The session mechanism uses a solution that maintains state on the server side. At the same time, we also see that because of the server-side hold state of the scheme in the client also need to save an identity, so the session mechanism may need to use the cookie mechanism to achieve the purpose of preserving the identity. The session provides a convenient way to manage global variables.



Session is for each user, the value of the variable is saved on the server, with a sessionid to distinguish which user session variable, this value is accessed by the user's browser when the server is returned, when the customer disables the cookie, This value may also be set to be returned to the server by get.



As far as security is concerned: when you visit a site that uses a session and create a cookie on your own machine, it is recommended that the session mechanism on the server side be more secure because it does not arbitrarily read the information stored by the customer.



Second, session mechanism



The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.



When a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID (called the session ID.), and if it is included, it has previously created a session for this client. The server will follow the session ID to retrieve the session (not retrieved, a new one), if the client request does not include session ID, then create a session for this client and generate a session ID associated with this session, The value of session ID should be a string that is neither duplicated nor easy to be found, and the session ID will be returned to the client in this response to save.



This session ID can be saved by using a cookie, so that the browser can automatically play the logo to the server during the interactive process. Generally the name of this cookie is similar to Seeesionid. However, a cookie can be artificially banned, and there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned.
A technique that is often used is called URL rewriting, which attaches the session ID directly behind the URL path. There is also a technique called form-hidden fields. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted.



Both the cookie and session can be tracked, but the principle of completion is not quite the same. Under normal circumstances both can satisfy the demand, but sometimes can not use the cookie, sometimes can not use the session.



The following is a comparison of the characteristics of the two and the place of application.



1. Different access modes



Only ASCII strings can be stored in a cookie, and if the requirement is to access Unicode characters or binary data, the requirement is first encoded. There is no direct access to Java objects in cookies. To store slightly more complex information, it is difficult to use cookies.
In the session, you can access any type of data, including not limited to string, Integer, List, map, and so on. Session can also be directly stored in Java beans and even any Java class, objects, etc., the use of very easy. The session can be considered a Java container class.



2. Differences in privacy policies



Cookies are stored in client-side readers and are visible to clients, and some programs on the client may snoop, copy, or modify the contents of a cookie. The session is stored on the server, is transparent to the client, and there is no risk of sensitive information disclosure.
If you choose a cookie, the best way is to try not to write sensitive information, such as your account password, to the cookie. It is best to encrypt the cookie information like Google and Baidu, submit it to the server, and then decrypt it to ensure that the information in the cookie can be read as long as I understand it. And if the choice session is more convenient, anyway, is placed on the server, the session of any privacy can be effectively protected.



3. The difference in validity



Anyone who has used Google knows that Google's login information is valid for a long time if they sign in to Google. Google will permanently record the user's login information without having to log back in every visit. To achieve this effect, it is a good choice to use cookies. You only need to set the cookie expiration time property to a very large number.



Since the session relies on a cookie named Jsessionid, and the cookie Jsessionid expiration time is acquiesced to –1, simply close the reader the session will be invalidated, so the session can not complete the information forever effective effect. Using URL rewrite can not be done. And if the timeout period of the set session is too long, the server accumulates more sessions, the more likely to incur memory overflow.



4. Differences in server pressure



Session is stored on the server side, each user will produce a session. If the number of concurrent access users is very large, it will produce a lot of sessions, consuming a lot of memory. Therefore, like Google, Baidu, Sina such a high number of concurrent visits to the site, is unlikely to use the session to track customer sessions.



While the cookie is stored on the client, it does not occupy server resources. Cookies are a good choice if you have a lot of concurrent readers. For Google, Baidu, Sina, cookies may be the only option.



5. browser support for different



Cookies are supported by the client browser. If the client disables cookies or does not support cookies, session tracking is invalidated. With regard to WAP applications, regular cookies are useless.



If the client browser does not support cookies, you need to use session and URL rewrite. It is important to note that all the URLs used in the session program are URL-rewritten, otherwise the session track will fail. For WAP applications, Session+url address rewriting may be its only option.



If the client supports cookies, the cookie can be both set to the browser window and the child window is valid (setting the expiration Time to –1), or it can be set to be valid in all reader windows (set the expiration time to an integer greater than 0). However, the session can only be valid within the Reader window and its subwindow. If two browser windows are irrelevant, they will use two different sessions. (IE8 under different window sessions coherent)



6. Differences in cross-domain support



Cookies support cross-domain access, such as setting the Domain property to ". Biaodianfu.com", and all domain names with the suffix ". biaodianfu.com" are able to access the cookie. Cross-domain cookies are now commonly used in networks such as Google, Baidu, Sina, and so on. The session does not support cross-domain access. The session is valid only within the domain where he is located.
Only using cookies or simply using the session may not achieve the desired results. At this point, you should try to use both cookies and session. The combination of cookie and session will accomplish many unexpected effects in practical projects.





The use of cookies in PHP and session:


When setting up an array of cookies in PHP, you cannot use the same method of adding data as in PHP:






<?php
Setcookie(‘my_cookie[]‘, 1);
Setcookie(‘my_cookie[]‘, 2);
Print_r($_COOKIE); // Array ( [my_cookie] => Array ( [0] => 1 ))
                       // The value of the array is added successfully, but the index has not changed, and the data behind it will be overwritten!
From this
        My_cookie[], which defaults to the location of the first element of the data, ie the index is
The position of 0. Note that it is different from the one in php! Use the cookie data to remember to specify the index of the array element later!

$my_cookie[] = 1;
$my_cookie[] = 2;
Print_r($my_cookie); //Array ( [0] => 1 [1] => 2)
?>

Two ways to delete a cookie variable:
1.php





<?php
Setcookie(‘user_name_1‘, ‘zhaofei299‘, time()+3600); // lifetime is 1 hour
Setcookie(‘user_name_2‘, ‘ZHAOFEI299’, time()+3600); // lifetime is 1 hour
?>





2.php






<?php
Setcookie(‘user_name_1‘); // first
Setcookie(‘user_name_2‘, "", time()-1); // second
Print_r($_COOKIE); // Refreshing page 2 will output Array ( [user_name_1] => )

/*Why is the user_name_1 in the super global variable $_COOKIE not deleted (the variable is empty does not mean it does not exist), and
User_name_2 was deleted? That's because the two ways to delete variables are different!
The first one: set the lifetime of the cookie, just set its value to null by default, the lifetime is the same as the browser, the browser
When it is closed, the cookie will be deleted! So when you reopen a browser and output the address, you will find that the cookie variables are all deleted!
Comment out the two setcookie() functions in 2.php (re-export the address)!
The second type: also sets the lifetime of the cookie, so that the lifetime of the cookie must expire, and the cookie is deleted, so the brush
On the new page, when the client sends a cookie to the server, $_COOKIE does not get the value of the cookie variable!
*/
?>







The session ID is stored in the client cookie by default!





<?php
session_start(); 
print_r($_COOKIE); 
?>





There are two ways to set up cookies





header(‘set-cookie:user=zhaofei299‘);
setcookie(‘user‘, ‘zhaofei299‘);


Session variables cannot be overloaded with Get data or post data!
Using the session variable to pass an array, the object is not serialized!
When passing an object using the session variable, you must include the definition of the class object before calling Session_Start (), deserializing
(serialize)!
Deleting a single session variable can be deleted directly using unset ($_session[' * * *))!
Deleting all session variables can not be used with unset ($_session), as this will delete all session information, including stored in the cookie
PHPSESSID, which destroys the conversation between two pages, should use $_session = Array ();
Eliminate the session ID and lose contact between pages!
Session_destroy ();
Program Listing 1.1





<?php
Session_start();
Header(‘content-type:text/html;charset=utf-8‘);
$_SESSION[‘a‘] = ‘a‘;
$_SESSION[‘b‘] = ‘b‘;
Unset ($_SESSION); / / after the test, then take a look at it
$_SESSION[‘user‘] = ‘zhaofei299’;
Echo ‘SESSION_ID: ‘.session_id().‘<br />’;
Echo ‘<a href="3.php" target="_blank">Test under</a> ‘;
?>




<?php
Session_start();
Echo $_SESSION[‘user‘];
Echo session_id(); //The session variable has changed
?>





Two ways to pass the session ID (session_id):
1.cookie
2.url
Because the default session is cookie-based and the cookie is sent with the HTTP protocol, as with cookies, the
Session_Start () cannot have any output before!
Now I'm talking about the second, passing the session ID through a URL
This constant in PHP defines the SID to get the ID of the session
Use of sesssin_id:





<?php
Session_start();
Echo defined (‘SID‘)?‘true’: ‘false‘; // true
Echo SID; //Nothing?
?>





Why is Sid's value null? What's wrong with it?
The reason is because the session is cookie-based by default, and the SID only session_id through the URL
The value will be assigned only when the data is passed!
Disable the cookie in the browser and you will see that the SID has output, not null!
Delete session
Be implemented in three steps.





<?php
Session_destroy(); // Step 1: Delete the server-side session file, which is used
Setcookie(session_name(), ‘‘, time()-3600); // Step 2: Delete the actual session:
$_SESSION = array(); // Step 3: Delete the $_SESSION global variable array
?>





We all know that the session variable is stored on the server side, that is, the session variable will be saved in a directory in the server, I
You can find the address saved in the session file in the Session.save_path in php.ini.

The lifetime of the default session is the end of the browse close, but to know when the session expires, when the page Session_Start () is opened
Determine if the session ID exists, create one if it does not exist, or load the session ID variable into the page! Because expiration session_id will
A new is created, but it is saved on the server side of the session file and is not deleted (Close browser, open session file Save
Session_destory () function to clear the session ID and clear the corresponding session file, so that the most
Thorough removal!

session_id uses a URL to pass session variable data, because Session_Start () determines whether the session ID is stored when the session is opened
In, create one if it doesn't exist, or load the session ID variable into the page!

Instead, the URL is used to pass the session_id, but each refresh/entry page generates a session ID, so the page is
You can't get session_id variables set on another page, so using a session doesn't make sense!

Workaround: before Session_Start (), manually set the page's session_id so that the page can be set on the previous page
Session variable, it also realizes the transfer of the conversation, the following code can be explained!





//Disabled cookies
1.php

<?php
Session_start();
$_SESSION[‘user‘] = ‘zhaofei299’;
Echo ‘<a href="2.php?‘.SID.‘">Next page</a> ‘;
?>


The 4th line of code in 1.php can also be written as: Echo ' <a href= ' 2.php ' > Next </a> ';
You can set session.use_trans_sid in php.ini to 1 so that when you pass the session ID using a URL,
The browser will automatically append the session_id to the URL!
It's like typing in the browser: www.baidu.com, the browser will automatically change it to http://www.baidu.com/

2.php





<?php
Session_id($_GET[‘PHPSESSID‘]); // Set session_id manually, this will use the previous page
The session_id variable has been implemented, and the session is implemented!
Session_start();
Print_r($_SESSION);
?>





Commonly used session functions:





Bool session_start(void); Initialize session
Bool session_destroy(void): Delete the server-side session association file.
String session_id() current session id
String session_name() The name of the session currently accessed, which is the cookie name of the client holding the session ID. Default
PHPSESSID.
Array session_get_cookie_params() Details of the session associated with this session.
String session_cache_limiter() Controls the client-side caching of pages using sessions
Ini session_cache_expire() controls client cache time
Bool session_destroy() Delete the file that saves the session information on the server side.
Void session_set_cookie_params ( int lifetime [, string path [, string domain [, bool
Secure [, bool httponly]]]] ) sets the details of the session associated with this session
Bool session_set_save_handler ( callback open, callback close, callback read, callback
Write, callback destroy, callback gc ) defines the function that handles the session, (not using the default method)
Bool session_regenerate_id([bool delete_old_session]) assigns a new session id





The similarities and differences between cookies and sessions in PHP and their use


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.