Session usage in php

Source: Internet
Author: User
Tags php session php print
Visitors to the website will be assigned a unique identifier, the so-called session ID. It is either a cookie stored on the client or transmitted through a URL. Session support allows users to register any number of variables and keep them for use by each request. When a visitor accesses the website, PHP will automatically (if session. auto_start is set to 1) or

Visitors to the website will be assigned a unique identifier, the so-called session ID. It is either a cookie stored on the client or transmitted through a URL. Session support allows users to register any number of variables and keep them for use by each request. When a visitor accesses the website, PHP will automatically (if session. auto_start is set to 1) or

Visitors to the website will be assigned a unique identifier, the so-called session ID. It is either a cookie stored on the client or transmitted through a URL.
Session support allows users to register any number of variables and keep them for use by each request. When visitors visit the website, PHP will automatically (if session. auto_start is set to 1) or when a user request (explicitly called by session_start () or secretly called by session_register () checks whether a specific session ID is sent in the request. If yes, the previously saved environment is rebuilt.
2.1 transfer of sessionID
2.1.1 send sessin ID through cookie
Use session_start () to call the session. When the server generates the session file, it generates the session ID hash value and the session name with the default value PHPSESSID, and sends the variable (default) to the client) PHPSESSID (session name), with a 128-bit hash value. the server will use this cookie to interact with the client.
The session variable value is serialized in php and stored in a text file on the server. It interacts with the coolie whose client 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 ());
After you jump to a new page from this page and call session_start (), PHP checks the session data stored on the server that is associated with the given ID. If no session data is found, a new dataset is created.
2.1.2 send session ID through URL
This method is used only when the user disallows the use of cookies, because the browser cookie is already used. This method is not required for security purposes.
= "> Xxx, you can also pass the session value through POST.
2.2 Basic session usage example
// Page1.php
Session_start ();
Echo 'Welcome to page #1 ';
/* Create a session variable and assign a value to the session variable */
$ _ SESSION ['favcolor'] = 'green ';
$ _ SESSION ['animal '] = 'cat ';
$ _ SESSION ['time'] = time ();
// If the client uses cookies, the session can be directly transferred to page2.php.
Echo'
Page 2 ';
// If the client disables cookie
Echo'
Page 2 ';
/*
By default, in php5.2.1, SID only has a value when the cookie is written.
The corresponding cookie already exists, so the SID will be (undefined) null
*/
?>
// Page2.php
Session_start ();
Print $ _ SESSION ['animal ']; // print a single session
Var_dump ($ _ SESSION); // print the session value passed by page1.php.
?>

2.3 use the session function to control page cache.
In many cases, we need to determine whether our webpage is cached on the client or set the cache validity period. For example, we need to log on to the webpage to view some sensitive content, if the cache is cached locally, you can directly open the local cache to browse the webpage without logging on.
Use session_cache_limiter ('private'); to control the page client cache, which must be called before session_start.
For more parameters, see http://blog.chinaunix.net/u/27731/showart.php? Client Cache Control with id = 258087.
Use session_cache_expire (int) to control the Client Cache Time; unit (s). It must also be called before session_start.
This is only a method for controlling the cache when session is used. We can also control the page cache in header.
2.4 delete a session
Three steps are required.
Session_destroy (); // Step 1: Delete the session file on the server.
Setcookie (session_name (), '', time ()-3600); // Step 2: delete the actual session:
$ _ SESSION = array (); // Step 3: delete the $ _ SESSION global variable array
?>
2.5 session usage in PHP large-scale web Applications
The default session storage method is not suitable for websites with large traffic volumes. Currently, the optimal method is to access sessions using databases. at this time, the function bool session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, callback gc) is the solution to solve this problem.
The function uses the following six functions:
1. bool open () is used to open the session storage mechanism,
2. bool close () closes the session storage operation.
3. This function is used when mixde read () is installed in session data from the storage.
4. bool write () writes all data of the given session ID to the storage.
5. bool destroy () destroys the data associated with the specified session ID
6. bool gc () garbage collection of data in the storage system
For example, see the session_set_save_handler () function in the php manual.
If the class is used for processing, use
Session_set_save_handler (
Array ('classname', 'open '),
Array ('classname', 'close '),
Array ('classname', 'read '),
Array ('classname', 'write '),
Array ('classname', 'deststroy '),
Array ('classname', 'gc '),
)
Call the six static methods in the className class. You do not need to call static methods if you can change the object, but do not need to generate objects if you use static members. This provides better performance.
2.6 common session functions:
Bool session_start (void); initialize the session
Bool session_destroy (void): deletes the session associated files on the server.
String session_id () id of the current session
String session_name () indicates the name of the session currently accessed, that is, the cookie name used by the client to save the session ID. PHPSESSID is used by default.
Array session_get_cookie_params () details of the session associated with this session.
String session_cache_limiter () controls the client cache of pages using sessions
Ini session_cache_expire () controls the Client Cache Time
Bool session_destroy () deletes the file on the server that stores session information.
Void session_set_cookie_params (int lifetime [, string path [, string domain [, bool secure [, bool httponly]) sets 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 sessions (not by default)
Bool session_regenerate_id ([bool delete_old_session]) allocates a new session id

2.7 session Security Problems
By investing a lot of energy, attackers try to obtain valid session IDs of existing users. With session IDs, they may be able to have the same capabilities as this users in the system.
Therefore, our main solution is to verify the validity of the session ID.
If (! Isset ($ _ SESSION ['user _ agent']) {
$ _ SESSION ['user _ agent'] = $ _ SERVER ['remote _ ADDR ']. $ _ SERVER ['HTTP _ USER_AGENT'];
}
/* If the user's session ID is forged */
Elseif ($ _ SESSION ['user _ agent']! = $ _ SERVER ['remote _ ADDR ']. $ _ SERVER ['HTTP _ USER_AGENT']) {
Session_regenerate_id ();
}
?>

2.8 differences between Session passing through cookies and passing through SID:
Under the default configuration of the session in php5.2.1, when a session is generated, the server generates a pre-defined super global variable SID while sending the header set-cookie (that is, writing a cookie is equivalent to throwing a SID .), when $ _ COOKIE ['phpsessid '] exists, no cookie is written or the super global variable SID is generated. At this time, the SID is empty.

2.9 session instance
/**
* Verify the 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's session ID is forged, re-allocate the session ID */
Elseif ($ _ SESSION ['user _ agent']! = MD5 ($ _ SERVER ['remote _ ADDR ']
. $ _ SERVER ['HTTP _ USER_AGENT ']) {
Session_regenerate_id ();
}
}
/**
* Destroy a session
* Perfect implementation in three steps.
*
*/
Function sessionDestroy (){
Session_destroy ();
Setcookie (session_name (), '', time ()-3600 );
$ _ SESSION = array ();
}
?>

Note:
The cause of the session header message being sent is the same as that of the cookie.
In php5, the Registry configuration options of all php sessions are configurable during programming. In general, we do not need to modify the configuration. for more information about php session registry configuration options, see Session session processing functions in the manual.
During session data storage, the $ _ SESSION array is serialized for storage. Therefore, due to serialization problems, the values of special characters may be encoded using the base64_encode function, base64_decode is used for decoding when reading data.

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.