Dynamic web page technology PHP analysis on cookies and sessions
Author:Eve Cole
Update Time:2009-06-06 18:16:01
1. PHP COOKIE
A cookie is a mechanism that stores data on a remote browser to track and identify users.
PHP sends cookies in the header information of the http protocol, so the setcookie() function must be called before other information is output to the browser, which is similar to the restriction on the header() function.
1.1 Set cookies:
Cookies can be set using the setcookie() or setrawcookie() functions. It can also be set by sending 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
value: the value of the cookie variable
expire: the time when the validity period ends,
path: valid directory,
domain: valid domain name, unique top-level domain
secure: If the value is 1, the cookie is only valid on https connections, if the default value is 0, both http and https are valid.
example:
<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value); /* Simple cookie settings*/
setcookie("TestCookie", $value, time()+3600); /* Validity period is 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 the variable, but its subscript does not need quotes. In this way, you can use $_COOKIE['var']['a'] to read the COOKIE variable.
1.1.2. Use header() to set cookies;
header("Set-Cookie: name=$value[;path=$path[;domain=xxx.com[;...]]");
The following parameters are the same as those listed above for the setcookie function.
for example:
$value = 'something from somewhere';
header("Set-Cookie:name=$value");
1.2 Reading of Cookies:
You can directly use PHP's built-in super global variable $_COOKIE to read the cookies on the browser side.
In the above example, the cookie "TestCookie" is set. Now let's read it:
print $_COOKIE['TestCookie'];
Has the COOKIE been exported?!
1.3 Delete cookies
Just set the valid time to be less than the current time, and set the value to empty. For example:
setcookie("name","",time()-1);
Similar to using header().
1.4 Solving common problems:
1) There is an error message when using setcookie(). It may be because there is output or spaces before calling setcookie(). It may also be that your document is converted from other character sets, and the document may have a BOM signature at the end (that is, adding it to the file content Some hidden BOM characters). The solution is to prevent this situation from happening in your document. You can also handle it a little bit by using the ob_start() function.
2) $_COOKIE is affected by magic_quotes_gpc and may be automatically escaped
3) When using it, it is necessary to test whether the user supports cookies
<!--[if !supportLineBreakNewLine]-->
1.5 Cookie working mechanism:
Some learners are more impulsive and have no time to study the principles, so I put it later.
a) The server sets a cookie in the client by sending an http Set-Cookie header with the response (multiple cookies require multiple headers).
b) The client automatically sends an http cookie header to the server, and the server receives and reads it.
HTTP/1.x 200 OK
X-Powered-By: PHP/5.2.1
Set-Cookie: TestCookie=something from somewhere; path=/
Expires: Thu, 19 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 will create a cookie file on the client's disk and write:
TestCookie=something from somewhere;
/
This line is the result of using setcookie('TestCookie','something from somewhere','/');. It is also the result of using header('Set-Cookie: TestCookie=something from somewhere; path=/');.
<!--[endif]-->
2. PHP Session
The session uses a cookie with the expiration time set to 0, and uses a unique identifier called the session ID (a long string) to synchronize some session files on the server side (you can define the session storage type yourself), and communicate with the user Connected. The web application stores the data associated with these sessions and allows the data to be passed between pages with the user.
Visitors to the website are assigned a unique identifier, a so-called session ID. It is either stored in a client-side cookie or passed via the URL.
Session support allows users to register any number of variables and reserve them for each request. When a visitor accesses the website, PHP checks whether a specific session ID was sent in the request, either automatically (if session.auto_start is set to 1) or when the user requests it (explicitly called by session_start() or implicitly by session_register()). If so, the previously saved environment is recreated.
2.1 Transmission of sessionID
2.1.1 Transmit sessin ID through cookie
Use session_start() to call the session. While generating the session file, the server generates the session ID hash value and the session name with the default value of PHPSESSID, and sends the variable to the client (the default is) PHPSESSID (session name), with the value Is a 128-bit hash value. The server will interact with the client through this cookie.
The value of the session variable is serialized internally by PHP and stored in a text file on the server machine, and interacts with the client's coolie whose 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());
When jumping to a new page from this page and calling session_start(), PHP will check the server-side stored session data associated with the given ID. If not found, a new data set will be created.
2.1.2 Transmit session ID through URL
This method is only used when the user prohibits the use of cookies, because browser cookies are already universal, and for security reasons, this method is not needed.
<a href="p.php?<?php print session_name() ?>=<?php print session_id() ?>">xxx</a>, the session value can also be passed through POST.
2.2 Basic usage examples of session
<?php
// page1.php
session_start();
echo 'Welcome to page #1';
/* Create session variables and assign values to session variables */
$_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, under php5.2.1, the SID will only have a value when the cookie is written. If the session
The corresponding cookie already exists, then the SID will be (undefined) 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 page caching.
In many cases, we need to determine whether our webpage is cached on the client, or set the cache validity time. For example, there is some sensitive content on our webpage and you need to log in to view it. If it is cached locally, you can directly open the local cache. You can browse the web without logging in.
Use session_cache_limiter('private'); to control the page client cache, which must be called before session_start().
For more parameters, see client cache control at http://blog.chinaunix.net/u/27731/showart.php?id=258087 .
To control the client cache time, use session_cache_expire(int); unit (s). It must also be called before session_start().
This is only a method to control caching when using session. We can also control the caching of the page in header().
2.4 Delete session
It takes three steps to achieve.
<?php
session_destroy(); // The first step: Delete the server-side session file, this uses
setcookie(session_name(),'',time()-3600); // Step 2: Delete the actual session:
$_SESSION = array(); // Step 3: Delete the $_SESSION global variable array
?>
2.5 The use of session in PHP large-scale web applications. For sites with a large number of visits, the default session storage method is not suitable. The current best method is to use the database to access the session. At this time, the function bool session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, callback gc) are the solutions provided to us to solve this problem.
The 6 functions used by this function are as follows:
1. bool open() is used to open the session storage mechanism,
2. bool close() closes the session storage operation.
3. mixde read() Use this function when loading session data from storage
4. bool write() writes all data of the given session ID to storage
5. bool destroy() destroys the data associated with the specified session ID
6. bool gc() For an example of garbage collection of data in the storage system, see the session_set_save_handler() function in the PHP manual.
If you use classes to handle it, 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 6 static methods in the className class. ClassName can be changed to an object, so there is no need to call static methods. However, using static members does not require generating an object, and the performance is better.
2.6 Commonly used session functions:
bool session_start(void); initialize session
bool session_destroy(void): Delete server-side session associated files.
string session_id() ID of the current session
string session_name() The currently accessed session name, which is the cookie name where the client saves the session ID. The default is PHPSESSID.
array session_get_cookie_params() Session details associated with this session.
string session_cache_limiter() controls the client cache of pages using session
ini session_cache_expire() controls client cache time
bool session_destroy() deletes the file that saves session information on the server side
void session_set_cookie_params ( int lifetime [, string path [, string domain [, bool secure [, bool httponly]]]] ) Sets the 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 session (not using the default method)
bool session_regenerate_id([bool delete_old_session]) assigns a new session id
2.7 Session Security Issues Attackers put a lot of effort into trying to obtain the effective session ID of an existing user. With the session ID, they may be able to have the same capabilities as this user in the system.
Therefore, our main solution is to verify the validity 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();