Phpsession usage and security-PHP source code

Source: Internet
Author: User
Ec (2); session basic usage the sample copy code is as follows: & lt ;? Phppage1.phpsession _ start (); echoWelcometopage #1; * Create a session variable and assign a value to the session variable * $ _ SESSION [favcolor] green; $ _ SESSION [animal] cat; $ script ec (2); script

Basic session usage example
The Code is as follows:
// 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) blank */
?>
// 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, some sensitive content on our webpage can be viewed only after login. If it is cached locally, you can directly

After the local cache is opened, you can browse the webpage without logging in.
Use session_cache_limiter ('private'); to control the page client cache, you must

Called before session_start.
Client Cache control.
Use session_cache_expire (int) to control the Client Cache Time. The unit is (s ).

Called before session_start.
This is just a method to control the cache when session is used. We can also control the cache in header ().

Page cache.
2.4 delete a session
Three steps are required.
Session_destroy (); // Step 1: Delete the session file on the server, which 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 sessions in PHP large-scale web applications for sites with high access volumes, use the default session to store

The storage method is not suitable. Currently, the optimal method is to use the database tutorial to access the session. At this time, the function bool

Session_set_save_handler (callbackopen, callbackclose, callbackread,

Callbackwrite, callbackdestroy, callbackgc) is provided to us 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. Use this function when mixde read () is installed in session data from the storage. 4. bool write () will

Write all data of the given session ID to the storage. 5. bool destroy () destroys the session ID with the specified session ID.

Associated data 6. bool gc () for example of garbage collection of data in the storage system, see the php Manual

Session_set_save_handler () function.
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 six static methods in the className class. You do not need to call static methods if you can change the object.

Static members do not need to generate objects, and the performance is better.
2.6 common session functions:
Bool session_start (void); initialize the session
Bool session_destroy (void): deletes the session associated files on the server.

Stringsession_id () id of the current session
Stringsession_name () Name of the session currently accessed, that is, the name of the session ID that the client saves

Cookie name. PHPSESSID by default. Arraysession_get_cookie_params () corresponds

Details of the session associated with the session.
Stringsession_cache_limiter () controls the Client Cache ini for pages using sessions

Session_cache_expire () controls the Client Cache Time bool session_destroy () deletes the server

Void session_set_cookie_params (int lifetime

[, Stringpath [, stringdomain [, bool secure [, bool httponly ])

Bool session_set_save_handler (

Callbackopen, callbackclose, callbackread, callbackwrite,

Callbackdestroy, callbackgc) defines the function for processing the session (not the default method)
Bool session_regenerate_id ([bool delete_old_session]) allocates a new session

Id

2.7 session Security Issues attackers have invested a lot of energy in trying to obtain valid sessions of existing users.

With the session ID, they may have the same capabilities as the user 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 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:
In the default configuration of php5.2.1 session, when a session is generated, the server

Send the header set-cookie and generate the pre-defined super global variable SID (that is, write the cookie

It is equivalent to throwing a SID.) When $ _ COOKIE ['phpsessid '] exists, no cookie is written.

The super global variable SID is no longer generated. At this time, the SID will be empty.

2.9 session instance /**
* Verify the validity of the session *
*/FunctionsessionVerify (){
If (! Isset ($ _ SESSION ['user _ agent']) {
$ _ SESSION ['user _ agent'] = MD5 ($ _ SERVER ['remote _ ADDR ']
. $ _ SERVER ['HTTP _ USER_AGENT ']);
}
/* If the user's session ID is forged, 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 *
*/FunctionsessionDestroy (){
Session_destroy ();
Setcookie (session_name (), '', time ()-3600 );
$ _ SESSION = array ();
}
?>

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.