Dynamic Web technology PHP analysis of cookies and session

Source: Internet
Author: User
Tags bool garbage collection hash header session id variables php session valid


1. PHP Cookies



A cookie is a mechanism for storing data on a remote browser side to track and identify the user.
PHP sends cookies in the header information 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 cookies. You can also set it by sending the HTTP headers directly to the client.
1.1.1 Use the Setcookie () function to set cookies:
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: At the end of the validity period,
Path: Valid directory,
Domain: Valid domain name, top-level domain unique
Secure: If the value is 1, the cookie can only be valid on the HTTPS connection, and HTTP and HTTPS are available if the default is 0.
Example:
<?php
$value = ' something from somewhere ';



Setcookie ("TestCookie", $value); /* Simple Cookie settings * *
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 its sub domain name * *
?>



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



1.1.2. Use header () to set cookies;
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 reads:



Using PHP's built-in Super global variable $_cookie can read cookies on the browser side.
In the example above, the cookie "TestCookie" is set, and now we read:



Print $_cookie[' TestCookie '];



Is the cookie being exported?!



1.3 Deleting cookies
Simply set the valid time to less than the current time and leave the value blank. For example:
Setcookie ("name", "", Time ()-1);
Similar with header ().



1.4 FAQ Solutions:



1 when using Setcookie () there is an error prompt, possibly because the call to Setcookie () is preceded by an output or a space. It may also be that your documents are converted from other character sets, and the document may be followed by a BOM signature (that is, adding some hidden BOM characters to the file content). The solution is to keep this from happening in your document. There is also a point that can be handled by using the Ob_start () function.
2) $_cookie affected by MAGIC_QUOTES_GPC, may automatically escape
3 when used, it is necessary to test whether the user supports cookies
<!--[If!supportlinebreaknewline]-->



1.5 Cookie working mechanism:



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



http/1.x OK
x-powered-by:php/5.2.1
Set-cookie:testcookie=something from somewhere; path=/
Expires:thu, Nov 2007 18:52:00 GMT
Cache-control:no-store, No-cache, Must-revalidate, post-check=0, pre-check=0
Pragma:no-cache
Content-type:text/html



This line implements the cookie function, after receiving this line
Set-cookie:testcookie=something from somewhere; path=/
The browser creates a cookie file on the client's disk and writes it inside:
Testcookie=something from somewhere;
/
This line is the result of our use of Setcookie (' TestCookie ', ' Something from somewhere ', '/'); that is, using header (' set-cookie:testcookie=something from somewhere; path=/'); the result.
<!--[endif]-->



2. PHP session



The session uses a cookie with an expiration time of 0, and a unique identifier called a session ID (a long string of strings) synchronously generates some session files on the server side (you can define the save type for the session yourself). In connection with the user's organization. The Web application stores the data associated with these sessions and lets the data pass between the pages as the user.



Visitors to the site are assigned a unique identifier, known as the 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 reserve them for use by individual requests. When visitors visit the site, PHP automatically (if Session.auto_start is set to 1) or if the user requests (by Session_Start () explicitly called or Session_register () secretly called) to check whether the request sent a specific session ID. If so, the previously saved environment is rebuilt.



Transmission of 2.1 SessionID



2.1.1 Sessin ID via cookie



Using the Session_Start () call session, the server side generates the session ID hash value and the default value of Session name for PHPSESSID, while generating the session file, and sends the variable to the client (by default) PHPSESSID (session name), value 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 being serialized in PHP, and the variable name of the client corresponds to the PHPSESSID coolie by default.



That is, the server automatically sends HTTP headers: header (' Set-cookie:session_name () =session_id (); path=/');
namely Setcookie (Session_name (), session_id ());



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



2.1.2 The session ID by URL



This method is only used when the user prohibits the use of cookies, because the browser cookie is already common, and for security purposes, this method is not available.
<a href= "p.php?<?php print session_name () >=<?php print session_id ()?>" >XXX</A> You can also pass the session value by post.



2.2 Session Basic Usage example



<?php
page1.php
Session_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.php
Echo ' <br/><a href= ' page2.php ' >page 2</a> ';
If the client disables cookies
Echo ' <br/><a href= ' page2.php? Sid. ' >page 2</a> ';
/*
By default php5.2.1, the SID will have a value only if the cookie is written, if the session
The corresponding cookie already exists, then the SID will be (not defined) empty
*/
?>
<?php
page2.php
Session_Start ();
Print $_session[' animal ']; Print out a single session
Var_dump ($_session); Print out the session value passed by page1.php.
?>



2.3 Use the session function to control the page cache.



In many cases, we want to determine whether our web page is in the client cache, or to set the effective time of the cache, such as our web page has some sensitive content and to log in to see, if the cache to the local, you can directly open the local cache can not log in and browse to the page.



Use Session_cache_limiter (' private '); You can control page client caching, which must be called before Session_Start ().
See http://blog.chinaunix.net/u/27731/showart.php?id=258087 Client cache control for more parameters.



Control client cache time with session_cache_expire (int), unit (s), and before Session_Start ().



This is just a way to control caching using the session, and we can also control the caching of the page in header ().



2.4 Delete Session



Be implemented in three steps.



<?php
Session_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 the site with large traffic, the default session storage mode is not suitable, the best method is to use 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) provide us with solutions to this problem.
The function uses the following 6 functions:



1. bool Open () for opening session storage mechanism,



2. BOOL Close () closes the session store operation.



3. Mixde read () Use this function when the session data is mounted from storage



4. BOOL Write () writes all data for a given session ID to the store



5. bool Destroy () destroys data associated with the specified session ID






For example, see the PHP manual Session_set_save_handler () function.
If you are working with a class, you can use



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



Call 6 static methods in the ClassName class. ClassName can swap objects without invoking static methods, but with static members without generating objects, performance is better.



2.6 Common Session functions:



BOOL Session_Start (void); Initializing session
BOOL Session_destroy (void): Deletes a server-side session Association file.
String session_id () ID of the current session
String Session_name () The session name that is currently accessed, that is, the cookie name where the client holds the session ID. Default PHPSESSID.
Array Session_get_cookie_params () the details of the session associated with this session.
String Session_cache_limiter () controls client-side caching of pages that use session
INI session_cache_expire () control client cache time
BOOL Session_destroy () Deletes a file that holds 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 session associated with session
BOOL Session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, Callback G c) defines a function that processes sessions (not by default)
BOOL SESSION_REGENERATE_ID ([bool delete_old_session]) assigns a new session ID



2.7 Session security issues



By putting a lot of effort into trying to get a valid session ID for an existing user, the attacker might be able to have the same capabilities in the system as the user with the session ID.



Therefore, we mainly solve the idea is the effectiveness of the session ID.



<?php



if (!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 ();




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.