PHP session and Cookie usage instructions _php tips

Source: Internet
Author: User
Tags garbage collection http cookie md5 session id php session php print sessions sub domain
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 (Stringname [, stringvalue [, int expire [, Stringpath [, Stringdomain [, BOOL secure [, BOOL HttpOnly]]]] ] )
Name:cookie variable name Value:cookie The value of the variable expire: the end of the expiration time,
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, or HTTP and HTTPS if the default value is 0.
Example:
Copy Code code as follows:

<?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:
Copy Code code as follows:

$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 is 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, which receives the line after 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. 2.1 SessionID Transmission 2.1.1 Pass a cookie Sessin ID

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 ()?>" &GT;XXX&LT;/A&GT; You can also pass the session value by post.

2.2 Session Basic Usage example
Copy Code code as follows:

<?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 (); Step One: 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 large access sites, using the default session storage method is not suitable, the current optimal method is to use database access session. At this time, the function bool Session_set_save_handler (Callbackopen, Callbackclose, Callbackread, Callbackwrite, Callbackdestroy, CALLBACKGC) 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 () uses this function 4 when the session data is mounted from storage. BOOL Write () writes all the data for the given session ID to store 5. BOOL Destroy () destroys data 6 associated with the specified session ID. BOOL GC () A garbage collection example of data from a storage system is shown in the PHP manual Session_set_save_handler () function.
If you use a class to process, 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. STRINGSESSION_ID () ID of the current session
Stringsession_name () The session name that is currently accessed, that is, the cookie name where the client holds the session ID. Default PHPSESSID. Arraysession_get_cookie_params () The details of the session associated with this session.
Stringsession_cache_limiter () controls the client cache INI Session_cache_expire () that uses the session's page to control the client cache time bool Session_destroy () Deletes a file that holds session information on the server side void session_set_cookie_params (int lifetime [, Stringpath [, Stringdomain [, BOOL secure [, BOOL HTTP Only]]] set the details of the session associated with this session bool Session_set_save_handler (Callbackopen, Callbackclose, Callbackread, Callbackwrite, Callbackdestroy, CALLBACKGC) define functions that process sessions (not by default)
BOOL SESSION_REGENERATE_ID ([bool delete_old_session]) assigns a new session ID


2.7 session security The attacker could have the same capabilities in the system as the user, by investing a lot of effort in trying to get a valid session ID for an existing user, and with a conversation 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 ();
}
?>


2.8 Session passes through cookies and passes through the SID:
In the case of the default configuration of the php5.2.1 session, when the session is generated, the server side generates the predefined super global variable sid (that is, writing the cookie and throwing the SID) at the same time the header Set-cookie is sent. When $ _cookie[' Phpsessid ' exists, the COOKIE is no longer written, and the Super global variable SID is no longer generated, at which point the SID will be empty.


2.9 Session Use instance <?php
/**
* Validity of the session
*/functionsessionverify () {
if (!isset ($_session[' user_agent ')) {
$_session[' user_agent '] = MD5 ($_server[' remote_addr ')
. $_server[' http_user_agent ']);
}
* * Reassign session ID */elseif ($_session[' user_agent ']!= MD5 ($_server[' remote_addr ') if the user session ID is forged
. $_server[' Http_user_agent ']) {
SESSION_REGENERATE_ID ();
}
}

/**
* Destroy session
* Three steps to achieve the perfect, not leak *
*/functionsessiondestroy () {
Session_destroy ();
Setcookie (Session_name (), ", Time ()-3600);
$_session= Array ();
}
?>

Indicate:

The session header message has been sent 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 have to modify their configuration. To learn about PHP's session registry configuration options, refer to the Manual sessions processing function.
Session to save the data, is serialized $_session array to store, so there are serialization of the problem, there may be special characters to use the Base64_encode function code, read the time to use Base64_decode decoding

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.