Example analysis of the difference between cookie and session in PHP, _php tutorial of Cookie instance analysis

Source: Internet
Author: User
Tags http cookie php session php print php programming setcookie

Example analysis of the difference between cookie and session in PHP, cookie instance analysis


Cookies and sessions are very important techniques in PHP programming. In-depth understanding and mastering the application of cookies and sessions is the basis for PHP programming. This article analyzes the difference between the two in the form of examples. The specific analysis is as follows:

1.Cookie
A cookie is a mechanism for storing data on a remote browser to track and identify users.
PHP sends a cookie in the header of the HTTP protocol, so the Setcookie () function must be called before other information is exported to the browser, similar to the limit on the header () function.

1.1 Setting Cookies:
You can use the Setcookie () or Setrawcookie () function to set the cookie. It can also be set by sending HTTP headers 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
The value of the Value:cookie variable
Expire: The time at which the validity period ends,
Path: Valid directory,
Domain: Valid domain name, top-level domain unique
Secure: If the value is 1, the cookie is valid only on HTTPS connections, and HTTP and HTTPS are available if the default value is 0.
Example:

<?php$value = ' something from somewhere '; Setcookie ("TestCookie", $value); /* Simple cookie setting */setcookie ("TestCookie", $value, Time () +3600); /* Valid for 1 hours */setcookie ("TestCookie", $value, Time () +3600, "/~rasmus/", ". example.com", 1); /* Valid directory/~rasmus, valid domain name example.com and all sub-domains */?>

Set multiple cookie variables: Setcookie (' var[a] ', ' value '), use an array to represent the variable, but his subscript is not quoted. This allows you to read the cookie variable with $_cookie[' var ' [' a '].

1.1.2. Setting a cookie using the header ();

Header ("Set-cookie:name= $value [;p ath= $path [;d omain=xxx.com[; ...]];

The following parameters are the same as those listed above for the Setcookie function.
Like what:

$value = ' something from somewhere '; Header ("Set-cookie:name= $value");

1.2 Cookie read:
The browser-side cookie can be read directly with PHP's built-in Super global variable $_cookie.
The above example sets the cookie "TestCookie" and now we are reading:

Print $_cookie[' TestCookie '];

Is the cookie being exported?!

1.3 Deleting cookies
Just set the valid time to less than the current time, and leave the value blank. For example:

Setcookie ("name", "", Time ()-1);

Similar to the header ().

1.4 Frequently Asked questions resolved:

1) There is an error when using Setcookie (), possibly because there is an output or a space in front of the call to Setcookie (). It is also possible that your document will be converted from another character set, with a BOM signature behind the document (that is, adding some hidden BOM characters to the file contents). The solution is to keep your documents from happening. There is also a point that can be handled by using the Ob_start () function.

2) $_cookie affected by MAGIC_QUOTES_GPC, may be automatically escaped

3) When using, it is necessary to test whether the user supports cookies

1.5 Cookie working mechanism:
Some learners are more impulsive and have no mind to study the principle, so I put it back.
A) The server sets a cookie (more than one cookie) in the client computer by sending an HTTP Set-cookie header in response.
b) The client automatically sends an HTTP cookie header to the server and the server receives the read.

http/1.x okx-powered-by:php/5.2.1set-cookie:testcookie=something from somewhere; Path=/expires:thu, 18:52:00 Gmtcache-control:no-store, No-cache, Must-revalidate, post-check=0, pre-check=0 Pragma: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 client's disk, and write Inside:
testcookie=something from somewhere;

This line is the result of our use of Setcookie (' TestCookie ', ' Something from somewhere ', '/'); that is, with the header (' set-cookie:testcookie= something from somewhere; path=/'); the result.

2. Session
session uses a cookie that has an expiration time of 0, and a unique identifier called the Session ID (a long string of strings). The server-side synchronization generates some session files (you can define the save type of the session yourself) and connect with the user agency. The Web application stores the data associated with these sessions and lets the data pass through the pages as the user passes between them. The
visitor to the Web site is assigned a unique identifier, the so-called session ID. It is either stored on the client's cookie or passed through the URL.
Session support allows users to register any number of variables and keep them for use by individual requests. When a visitor visits a website, PHP automatically (if Session.auto_start is set to 1) or when the user requests (explicitly called by session_start () or Session_register () secretly calls) checks whether a specific session ID is sent in the request. If it is, the previously saved environment is rebuilt.

2.1 sessionid transfer

2.1.1 Transfer sessin ID via cookie

Using Session_Start () Call session, the server side generates session ID hash value and the default value is PHPSESSID session name, and sends the variable to the client (default). PHPSESSID (session name), which is a 128-bit hash value. The server side will interact with the client through this cookie.

The value of the session variable is stored in a text file on the server machine after the internal serialization of PHP, and the client's variable name is PHPSESSID by default for the coolie of the corresponding interaction.

That is, the server automatically sends an HTTP header:

Header (' Set-cookie:session_name () =session_id (); path=/');

That

Setcookie (Session_name (), session_id ());

When a new page jumps from the page and calls Session_Start (), PHP checks the session data for the server-side storage associated with the given ID, and creates a new dataset if it is not found.

2.1.2 Sending session ID via URL

This method is only used when the user prohibits the use of cookies, as browser cookies are already common and are not available for security purposes.

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

You can also pass the session value via post.

2.2 Session Basic Usage example

<?php//Page1.phpsession_start (); Echo ' Welcome to page #1 ';/* Create session variable and assign value to session variable */$_session[' favcolor '] = ' Green '; $_session[' animal '] = ' cat '; $_session[' time ' = time ();//If the client uses cookies, the SESSION can be passed directly to Page2.phpecho '
Page 2 ';//If the client disables Cookieecho '
Page 2 ';/* By default php5.2.1, the SID will have a value only if the cookie is written, and if the corresponding cookie for that session already exists, then the SID is (undefined) null */?>
<?php//Page2.phpsession_start ();p rint $_session[' animal '; Print out a single sessionvar_dump ($_session); Print out the session value that page1.php passed over?>

2.3 Use the Session function to control page caching.

In many cases, we want to determine whether our web page is cached on the client, or to set the cache's effective time, such as some sensitive content on our web page and to log in to view, if cached locally, you can directly open the local cache can not log in and browse to the Web.

Use Session_cache_limiter (' private '); You can control the page client cache and must be called before Session_Start ().
Controls the client cache time with session_cache_expire (int), unit (s), and is also called before Session_Start ().
This is just a way to control the cache using the session, and we can also control the cache of the control page in the header ().

2.4 Delete Session
Be implemented in three steps.

<?phpsession_destroy ();            The first step: Delete the server-side session file, which uses Setcookie (Session_name (), ", Time ()-3600); Step two: Delete the actual session:$_session = Array ();           Step three: Delete the $_session global variable array?>

The use of 2.5 session in PHP large Web applications

For sites with large access, the default session storage method is not suitable, the current optimal method is to use the database access session. At this point, the function bool Session_set_save_handler (callback open, callback Close, callback read, callback write, callback destroy, callback GC) are the solutions that are provided to us to solve this problem.
The 6 functions used by the function are as follows:
1.bool open () opens the session storage mechanism,
2.bool Close () closes the session store operation.
3.MIXDE read () Use this function when loading session data from storage
4.bool write () writes all data for the given session ID to the store
5.bool destroy () destroys data associated with the specified session ID
6.bool GC () garbage collection of data in the storage system
See the PHP manual Session_set_save_handler () function for examples.
If you use a class to process, use the

session_set_save_handler (Array (' ClassName ', ' open '), array (' ClassName ', ' close '), Array (' ClassName ', ' read '), array (' ClassName ', ' write '), array (' ClassName ', ' destroy '), Array (' ClassName ', ' GC '), 

The

calls the 6 static methods in the ClassName class. ClassName you can swap objects without calling static methods, but using static members does not produce objects, and it performs better.

2.6 commonly used session functions:
bool Session_Start (void); Initialize session
bool Session_destroy (void): Delete the server-side session Association file.
String session_id () The ID of the current session
String Session_name () the session name currently accessed, that is, the client saves the session The cookie name of the ID. Default PHPSESSID.
Array session_get_cookie_params () details of the session associated with this session.
String Session_cache_limiter () controls the client cache
INI Session_cache_expire () of the page that uses the session to control client cache time
BOOL Session_ Destroy () Delete the server-side file that holds session information
void session_set_cookie_params (int lifetime [, String path [, string domain [, bool SE Cure [, BOOL HttpOnly]]]) sets the details of the session associated with this session
BOOL Session_set_save_handler (callback open, callback Close, C Allback Read, callback write, callback destroy, callback GC) define the function that handles the session (not the default)
bool Session_regenerate_id ([ BOOL Delete_old_session]) assigns a new session ID

2.7 Session security issues

By investing a lot of effort in trying to get the valid session ID of an existing user, with the session ID, they are likely to have the same capabilities as this user in the system.
Therefore, our main approach is to validate the validity of 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 ();}? >

The 2.8 session is passed through a cookie and is passed through the SID differently:

In the case of the default configuration of the php5.2.1 session, when the session is generated, the server side will generate a pre-defined super global variable SID at the same time that the header Set-cookie is sent (that is, the write cookie and the thrown SID are equivalent.), when the $ _cookie[' Phpsessid ' is present, the COOKIE will no longer be written, and the Super global variable SID will no longer be generated, at which time the SID is empty.

2.9 Session Usage Example

<?php/*** 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, reassign session ID *  /elseif ($_session[' user_agent ']! = MD5 ($_server[' remote_addr ')  . $_ server[' Http_user_agent ')) {    session_regenerate_id ();  }} /*** destroy session* Three steps perfect realization, non-leakage **/function Sessiondestroy () {  Session_destroy ();  Setcookie (Session_name (), ", Time () -3600);  $_session = Array ();}? >

Note: The session header information has been issued for the same reason as a cookie.
In PhP5, the registry configuration options for all PHP sessions are programmable, and in general we do not need to modify their configuration. To learn about the session registry configuration options for PHP, refer to the session handler function at the manual.

It is believed that this article has a certain reference value for understanding the usage of cookies and session in PHP.


PHP session how to understand, and the difference between the cookie where? There are no specific examples

Session is a temporary user data saved on a server side of a Web service stateless session, which allows the server to reconstruct user session information.
Cookies are data retention functions that adapt to local script temporary data storage and session authentication with server-side interaction

Simply put, the session requires a cookie to be enabled for normal use.
When crawling an HTTP packet, it is found that cookie:phpsessid=xxxx is sent when the page content is requested, and Set-cookie:phpsessid=xxxx is included in the header information that is returned. If you change the value of this cookie in the header information, it will cause your user login status to change, because the server side can not find the corresponding session file according to the value of PHPSESSID.

If the server side only consider the initial html+ script to consider the way, there is no session of the file, because it is a static page, does not have a follow-up relationship with the server (put aside the AJAX request). So the cookie becomes the local storage file for the script to run. The cookie exists in the form of "Key name = key value", with ";" Separated.

The difference between the duration length:
A cookie has a defined duration that is longer than the length of time that the browser will consider outdated and will discard and delete this cookie file. Therefore, even if the server side of the session still exists, because the cookie information has been lost, unable to retrieve the corresponding PHPSESSID value to achieve the reconstruction of the session. If the timeout length is not defined, it is automatically invalidated when the browser is closed.
Session can specify the period of existence, if the time limit is exceeded, the PHPSESSID value of this cookie in the corresponding session has a request will automatically lengthen the length of time, until more than the length of the request will be cleared through the recovery mechanism, but not fully guaranteed to be properly recycled. If the cookie file is still stored locally, it cannot be rebuilt because the session file for the corresponding PHPSESSID is no longer present.

(PHP) session differs from Cookie

Session stores cookies for the server as client storage.
Yes, the biggest difference between the session and the cookie here is what I've done with the code and the relevant 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;
?>
Cookies:
(1) Used to store continuous access to a page. (That is, the value of the cookie to the ground is not the concept of a real global change, that is, for a1.php by adjusting $_cookie["XX") can invoke the corresponding cookie value, However, if you open a a2.php IE browser again, then take the cookie value will not be taken out! Therefore, it is not a global concept in real sense for cookies. )
(2) The cookie is stored in the client and is stored in the user win's temp directory for the cookie.

Session: (A special cookie, when the cookie is banned, the session will be banned, but the session can be redirected through the way to regain)
(1) A unique variable that can be used to store a user's global. For the session, you can redirect and get the value of the session via Session_Start (), and do the operation without having to browse for it to be opened again. If the above a1.php the session of the operation, if you open an IE after the use of Sessoin_start (), after the session corresponding variable will be re-enabled ... Remaining full text >>

http://www.bkjia.com/PHPjc/871100.html www.bkjia.com true http://www.bkjia.com/PHPjc/871100.html techarticle the analysis of the difference between cookie and session in PHP, cookie instance analysis cookie and session are very important techniques in PHP programming. An in-depth understanding and mastery of cookie and session applications is carried out ...

  • Related Article

    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.