1. How PHP Session Works
Session file is stored on the server side, by default, the directory saved by the session file is specified by Session.save_path, the file name is prefixed with Sess_, followed by the session ID, such as: Sess_ c72665af28a8b14c0fe11afe3b59b51b. Can be based on the session ID provided by the client to the user's file, get the value of the variable, session ID can use the client's cookie or Http1.1 protocol query_string (that is, the URL of the access "?" Later) to the server, and then the server reads the session directory. That is, the session ID is the ID that gets the session variable stored on the service.
When the Code session_start (), run, on the server generated a session file, followed by the only corresponding to a session ID, define the session variable to be stored in a certain form in the session file just generated. The session ID allows you to remove the defined variable. After the spread, in order to use the session, you must also execute session_start (); A session file will be generated, corresponding to the session ID, with this session The ID is not the variable in the first session file mentioned above, because the session ID is not the "key" to open it. If the Session_Start (), preceded by the code session_id ($session ID), will not generate a new session file, directly read the session file corresponding to this ID.
2. Session common functions and usage
2.1 session_start (): Starts a session or returns a session that already exists.
This function has no parameters and the return value is true. If you use a cookie-based session, the browser cannot have any output before using Session_Start (). can start in php.ini session.auto_start= 1, so you don't have to call Session_Start () before each session. However, there are some restrictions on enabling this option, and if you do enable Session.auto_start, you cannot put an object into a session because the class definition must be loaded before starting the session to rebuild the object in the session.
2.2 Register Session Variables:
PHP5 uses $_session[' xxx ']=xxx to register the SESSION global variable. Note Session_register (),
Session_unregister, session_is_registered is no longer used under PHP5, except in php.ini
Register_globle is set to ON, but it is strongly recommended to turn off register_globle for security reasons.
Http_session_vars also do not advocate the use of, the official proposed to replace it with $_session.
page1.php
Session_Start (); You must call this function before using the session.
$_session[' name ']= "I am a black tornado Li Kui!"; Register a Session variable
$_session[' passwd ']= "Mynameislikui";
$_session[' time ']=time ();
If the client supports cookies, you can pass the session to the next page through the link.
Echo '
Pass the session through a cookie;
This method is used to pass the session when the client does not support cookies.
Echo '
Pass the session via URL ';
page2.php
Session_Start ();
echo $_session[' name '];
echo $_session[' passwd '];
echo Date (' Y m D h:i:s ', $_session[' time ');
Echo '
Go back to the previous page ';
?>
2.3 session_id ([string $id]): Get and/or set the current session ID
The php5 can either use session_id (), or the session_id and Session_name of the current session can be obtained by appending the SID on the URL.
If session_id () has a specified value (that is, parameter $id is specified), the current session_id value is replaced. The session must be started before using the function: session_start ();
Example: Manually setting the lifetime of a session:
Session_Start ();
Save the day
$lifeTime = 24 * 3600;
Setcookie (Session_name (), session_id (), time () + $lifeTime, "/");
?>
In fact, the session also provides a function session_set_cookie_params (); To set the lifetime of the session, the function must be called before the session_start () function call:
Save the day
$lifeTime = 24 * 3600;
Session_set_cookie_params ($lifeTime);
Session_Start ();
$_session["Admin"] = true;
?>
If the client uses IE 6.0, session_set_cookie_params (); There are some problems with the function setting cookie, so let's call the Setcookie function manually to create a cookie.
2.4 Check if the session exists?
In previous versions of PHP, Session_is_register () was commonly used to check if a session exists, and if you use $_session[' XXX ']=xxx to register a conversation variable, session_is_register () function no longer works. You can use
Isset ($_session[' xxx ') to replace.
2.5 Change session_id session_regenerate_id ([bool $delete _old_session]) The change succeeds returns True, and the failure returns false.
Use this function to change the session_id for the current session, but does not change the other information for the current session by default, unless $delete_old_session is true. For example:
Session_Start ();
$old _sessionid = session_id ();
SESSION_REGENERATE_ID ();
$new _sessionid = session_id ();
echo "Original SessionID: $old _sessionid
";
echo "New SessionID: $new _sessionid
";
Echo
";
Print_r ($_session);
Echo
";
?>
2.6 Session_name () returns the name of the current session or changes the name of the current session. If you want to change the name of the current session, you must call the function before Session_Start (). Note: Session_name cannot consist of numbers only, it contains at least one letter. Otherwise, a new session ID will be generated at every moment of the day.
Example of Session renaming:
$previous _name = Session_name ("WebSiteID");
echo "The new session name is: $previous _name
";
?>
2.7 How to delete a session
(1) unset ($_session[' xxx ']) delete a single session,unset ($_session[' xxx ') to unregister a registered SESSION variable. Its effect is the same as Session_unregister (). Session_unregister () is no longer used in PHP5 and can be limbo.
Unset ($_session) This function must not be used, it will destroy the global variable $_session, and there is no viable way to restore it. Users can no longer register $_session variables.
(2) $_session=array () delete more than one SESSION
(3) Session_destroy () ends the current session and empties all resources in the session. The function does not unset the global variable (globalvariables) associated with the current session, nor does it delete the client's session cookie. PHP's default session is cookie-based, and if you want to delete a cookie, you must use the Setcookie () function.
The following is the official PHP case to delete the session:
Initializes the session.
Session_Start ();
/*** Delete all the session variables: Unset ($_session[xxx]) can also be deleted individually. ****/
$_session = Array ();
/*** Delete the Sessin ID. Because the session is cookie-based by default, use Setcookie to delete the cookie.***/that contains the session ID.
if (Isset ($_cookie[session_name ())) {
Setcookie (Session_name (), ", Time ()-42000, '/');
}
Finally, the session is completely destroyed.
Session_destroy ();
?>
Thus we can draw the steps to delete the session:
①session_start ()
②$_session=array ()/unset ($_session[' xxx ')
③session_destroy ()
3. Session cross-page delivery problem:
3.1 There are two ways to pass a session Id:cookie URL parameter
The session module supports both of these methods. Cookies are more optimized, but they also provide alternative methods because they are not always available. The second method embeds the session ID directly in the middle of the URL.
PHP can transparently convert the links between pages. If you use a version that is lower than PHP 4.2, you will need to manually activate it when you compile PHP, and under UNIX, use the--ENABLE-TRANS-SID configuration option. If both this configuration option and the Run-time option Session.use_trans_sid are activated (modify php.ini), the relative URI is automatically modified to contain the session ID.
Note: A non-relative URL is assumed to point to an external site, so there is no additional SID, because this can be a security risk of leaking SIDS to different servers.
In addition, you can also use a constant SID. If the client does not send a session cookie, the SID is in the format session_name=session_id, otherwise it is an empty string. Therefore, it can be embedded into the URL unconditionally.
3.2 solve the session cross-page transmission problem three ways
The ① client has disabled cookies.
② browser problems, temporarily unable to access cookies
Session.use_trans_sid = 0 in ③php.ini or--ENABLE-TRANS-SID option is not turned on at compile time
When the client's cookie is disabled or there is a problem, PHP automatically attaches the session ID to the URL, so that the session ID can be used across the page to use the session variable. But this kind of attachment also has certain condition: "session.use_trans_sid in php.ini = 1 or open--enable-trans-sid option at compile time";
Having understood the above, we can draw three ways to solve the problem of cross-page transmission:
1. Set session.use_trans_sid = 1 in php.ini or open the--ENABLE-TRANS-SID option at compile time to have PHP automatically pass the session ID across pages.
(Some people say: But in the test, modify php.ini which way in the page with the header (' location:xx.php ') and JavaScript window.location=xx.php the case does not achieve the desired effect. Currently found in XX normal. )
2, manually pass the URL value, hide the form passed session ID.
3, file, database and other forms to save session_id, in the process of cross-page manual call.
The following examples illustrate:
First case:
page1.php
Session_Start ();
$_session[' var1 ']= "People's Republic of China";
$url = "Next page";
echo $url;
?>
page2.php
Session_Start ();
echo "passes the value of the SESSION variable var1:". $_session[' var1 ');
?>
Running the above code, in case the client cookie is normal, should be able to get the result "People's Republic of China".
Now you manually shut down the client's cookie and run it, you may not get the result. If you don't get the results, then "set Session.use_trans_sid = 1 in php.ini" or "open--enable-trans-sid option at compile time" and get results "People's Republic of China"
The second way:
s1.php
Session_Start ();
$_session[' var1 ']= "People's Republic of China";
$SN = session_id ();
PHP5 defines a constant SID to represent session_id (), $url can also be written $url= ' next page ';
$url = "Next page";
echo $url;
?>
s2.php
session_id ($_get[' s ');
Session_Start ();
echo "passes the value of the SESSION variable var1: www.2cto.com". $_session[' var1 '];
?>
The Third Way:
Login.html
<title>Login</title>
Please login:
mylogin1.php
$name =$_post[' name '];
$pass =$_post[' pass ';
if (! $name | |! $pass) {
echo "User name or password is blank, please login again";
Die ();
}
if (! ( $name = = "Laogong" && $pass = = "123")) {
echo "username or password is incorrect, please login again";
Die ();
}
Registered users
Ob_start (); Turn on output buffering
Session_Start ();
$_session[' user ']= $name;
$psid =session_id ();
$FP =fopen ("E:\\tmp\\phpsid.txt", "w+");
Fwrite ($fp, $psid);
Fclose ($FP);
Authentication successful, related operations
echo "Logged in
";
echo "Next page";
?>
mylogin2.php
$FP =fopen ("E:\\tmp\\phpsid.txt", "R");
$sid =fread ($FP, 1024);
Fclose ($FP);
session_id ($SID);
Session_Start ();
if (Isset ($_session[' user ") && $_session[' user ']=" Laogong ") {
echo "Logged in!";
}
else {
Successful login for related operations
echo "Not logged in, not authorized to access";
echo "Please login and browse";
Die ();
}
?>
4. A workaround for multiple servers sharing the same session
Slightly larger sites, usually have several servers, each server running a different function of the module, the use of different two-level domain names, and a strong overall site, the user system is unified, that is, a set of user names, passwords in the entire site of the various modules can be logged in use. Each server sharing user data is relatively easy to implement, only need to put a database server on the back end, each server through the unified interface to access user data. However, there is still a problem, that is, after the user login to another server after the other module, still need to log back in, this is a login, all the problems, mapping to the technology, in fact, how each server to achieve sharing session data problem.
To share session data, two goals must be achieved: one is that each server must have the same session ID as the same client, and it can be passed through the same cookie, which means that each server must be able to read the same name as Phpsessid And the other is how the session data is stored/placed to ensure that each server has access to it. In short, the session ID of the multi-server shared client, and the server-side session data must also be shared.
The first goal of the implementation is very simple, only need to set the domain of the cookie special, by default, the domain of the cookie is the domain name/IP address of the current server, and the domain is different, the individual server set cookies are not mutually accessible, Servers such as www.2cto.com are not able to read and write cookies that are set by the www.bbb.com server. Here we say that the server of the same site has its particularity, that is, they belong to the same domain, such as: Aaa.infor96.com and www.infor96.com belong to the domain. infor96.com, then we can set cookies The domain is. infor96.com so that aaa.infor96.com, www.infor96.com, and so on can access this cookie. The Setup method in the PHP code is as follows:
CODE:
Ini_set (' Session.cookie_domain ', '. infor96.com ');
The implementation of the second goal can use file sharing, such as NFS, but the setup, operation is somewhat complex. We can refer to the previous method of unified user system, that is, using a database to save session data, so that each server can easily access the same data source, to obtain the same session data.
about how to put the session into the database can be seen in the "PHP programming", and the following Web page
http://www.eb163.com/article.php?id=75&PHPSESSID=d226cc07cec0580ec7dad47119ee4667 excerpt from Hata Lishin's Crazy coding life
http://www.bkjia.com/PHPjc/478394.html www.bkjia.com true http://www.bkjia.com/PHPjc/478394.html techarticle 1. PHP session working principle the session file is stored on the server side, by default, the directory saved by the session file is specified by Session.save_path, the file name is prefixed with Sess_, followed by s ...