This article introduces to you about how to put the session into the database in PHP and use (with code), there is a certain reference value, the need for friends can refer to, I hope to help you.
Example Description:
It is safer to store session data variables on the server side, but imagine that a large web site with tens of millions of users, such as Xiaonei, will consume huge amounts of server resources if all user session data is stored on the server side. So when a programmer makes a large web site, It is safe to store the session on the server side, but it is not the best choice. If you store session data in a database, you can mitigate the server's The pressure data is also relatively safe.
Design process
First, create a table that stores the session in the MySQL database:
Table name is T_session
Table structure is
Description: Session_key: is used to save the session ID.
Session_data: Is the value used to store the serialized $_session[];
Session_time: is used to store time stamps, this timestamp refers to the current session at the time of creation of the time () +session validity. It is important to note that the type of session_time here is int, so that you can compare the size when manipulating the database!
So what is serialization?
Serialization (serialization) is the process of translating the state information of an object into a form that can be stored or transmitted. During serialization, an object writes its current state to a temporary or persistent store. Later, the object can be recreated by reading or deserializing the state of the object from the store.
For example
$_session["User"]= "Zhang San" $_session["pwd"]= "Zhangsan"
A string after a sequence of words
User|s:6: "Zhang San";p wd|s:8: "Zhangsan";
where s represents a type of string and the number represents the length of the strings so that the string can be manipulated.
And then there's the body part.
Session.save_handler defines the name of the processor that stores and obtains the data associated with the session. The default is files. If set to files (Session.save_handler = files), the PHP built-in mechanism is used, and if you want to customize the way you store it (such as in a database), use Session_set_save_handler () to customize the settings , We are talking about the second kind.
so we need to change the php.ini file. Session_set_save_handler value, modify it to user,
BOOLSession_set_save_handler ( callable Open , callable $close , callable Read , callable Write , callable Destroy , callable GC [, callable $create _sid [, callable Validate_sid [, callable Update_timestamp ]]] )
If you don't change it, you can use the session without having to talk to him, but when you change it, you have to face him. This is a very special function, because the parameters of the general function are variables, but the function's parameters are 6 functions (the following three parameters are optional parameters, can be ignored) do not fear, one to:
The first parameter: open (Save_path,session_name), the two parameters in this is automatically passed by PHP. Save_path in the case of Session.save_handler = files, it is Session.save_path,session_name is the session ID that the server uses to identify the client, but if the user is self-determined, This two parameter is not used, only in which the database is connected, the open callback function is similar to the constructor of the class, which is called when the session is opened. This is the first callback function that is called automatically after a session is started or the session is manually started by calling Session_Start (). This callback function successfully returns TRUE and returns FALSE instead.
The second parameter: close (), this function does not require parameters to close the database. The close callback function resembles a destructor for a class. Called after the write callback function is called. The close callback function is also called after the Session_write_close () function is called. This callback function successfully returns TRUE and returns FALSE instead.
The third parameter: read ($key), where the argument is the session id,php automatically passed, the precondition is that there is a session ID, if none, then this parameter returns an empty string. Note that if there is no corresponding data in the database must return an empty string, otherwise error! If there is data in the session, the read callback function must return the string after the session data is encoded (serialized) (here is the session_data removed from the table t_session). After you start the session automatically or by calling the Session_Start () function to start the session manually, PHP internally calls the read callback function to get the session data. Before calling read, PHP calls the open callback function. The serialized string format returned by the read callback must be in exactly the same format as the write callback function when the data is saved. PHP automatically deserializes the returned string and populates the $_session Super global variable.
The fourth parameter: write ($key, $data), which PHP automatically passes to this function, $key corresponding session id,$ Data corresponds to the current (because the write function is typically called after the end of the script execution) the SESSION variable that the script is processed by the serialization processor (as mentioned above $_session["user"]= "Zhang San" $_session["pwd"]= " Zhangsan "), the process of serializing session data is done by PHP based on the Session.serialize_handler setpoint. The serialized data is then associated with the session ID to be saved. When the read callback function is called to fetch data, the data returned must be fully consistent with the data passed into the write callback function. PHP calls this callback function after the script has finished executing or after calling the Session_write_close () function. Note that after this callback function is called, the close callback function is called inside PHP.
Note: PHP will call the write callback function after the output stream has been written and closed, so the debug information in the write callback function is not output to the browser. If you need to use debug output in the write callback function, we recommend that you write the debug output to a file.
The fifth parameter: destroy ($key), this callback function is called when the Session_destroy () function is called, or the session_regenerate_id () function is called and the Destroy parameter is set to TRUE. Used to unregister the session key value of the session, this callback function successfully returns TRUE, and conversely returns FALSE. It is a function that people often use when they click Log-off. There will be this little detail in the back.
The sixth parameter: GC (EXPIRE_TIME), the parameter of this function is the default mechanism of the Session.gc_maxlifetime setting of the session effective time. However, the expiration time of the session under the user mechanism is in the table session_time, so there is no need to pass parameters. In order to clean up the old data in the session, PHP calls the garbage collection callback function occasionally. The call cycle is controlled by the session.gc_probability and Session.gc_pisor parameters. This callback function successfully returns TRUE and returns FALSE instead.
At this point six functions have been introduced, but there are a number of things to note:
1, in the Open function is intended to pass the Save__path, the purpose is to find the file corresponding to the Session_name in this path, and then through the read () function reading the data, and then through the deserialization processor will be taken to the string deserialized, The $_session is automatically populated with various super global changes via PHP . or the Write function to save the serialized data to a file under this path. Then the path in this is not the default mechanism is not necessary, the answer is affirmative *_*. When the debug output is session_save_path under a non-default mechanism, the result is null, and if the stored path is not set, the $_session variable that is filled can be used only on the current page and not on another page. You can test this by opening the session on another page with the Session_Start () function , and then outputting session_id and Var_dump ($_session), which is the session_id of the server to the client last time it was browsed, But the $_session output is an empty array (of course I'm just about to say a bit about the process I'm validating). In fact, what I want to say is that we do not need to customize the path of the session when the storage mechanism, or why should be stored in the database?
So how can you read the values in $_session[] on other pages?
Introduce this function to put six callback functions and Session_set_save_handler into a file, and then introduce it with include () before Session_Start ()!
2. What is the order of their execution? A little dizzy, to summarize: first the session_start () function opens the session operation handle, and then the read function reads the data, when the script execution is finished executing the Write function and then the close function if there is session_ Destroy () is executed.
3, I mentioned above PHP will call the write callback function after the output stream has been written and closed. This can play me bad, small in the above can be around for a long time, or I will not be in the Write function debugging so long! But I also understand register_shutdown_function this function, the following is attached to the feature of this function:register_shutdown_function() is to call a function after all the PHP statements have been executed, and do not understand that the function is called when the client closes the stream browser page.
You can understand the invocation condition this way:
1. When the page is forcibly stopped by the user
2. When the program code runs over time
3. When PHP code execution is complete, the code executes with exception and error, warning
All right, all the above is said, enclose the code:
index.php User Login Interface
<?phpinclude ("session_set_save_handler.php");//introduce a custom session storage mechanism if (isset ($_get["Login")) {//To determine if login has a value, If the value is to be logged off, session_start (),//As long as the need to use the $_session variable, you need to open the callback function Opensession_destroy ();//Here is the small details mentioned above, when there is session_ Destroy, it is the}else{session_start (), which is executed before the read callback function, if (Isset ($_session["user")) {//Determines whether this value is defined, or if there is a definition, the session has not expired , go directly to the main content echo "<script>alert (' You've just been here recently '); window.location.href= ' main.php ';</script>";}? >
index_ok.php form Submission Processing file
<?phpinclude ("session_set_save_handler.php"); Session_Start (); if ($_post["sub"]) {//$_post["sub"] if it has a value, it is. Submit Query Echo $_post["sub"];if ($_post["user"]!= "" &&$_post["pwd"]!= "") {$_session["user"]=$_post["user"];$_ session["pwd"]=$_post["pwd"];//here the custom session management mechanism will invoke the callback function write, which will have been processed by the serialization processor (formed by the $_session[] variable) string to the database echo "< Script>alert (' Login successful! '); window.location.href= ' main.php ';</script> ";}}? >
main.php Main content Page
<?phpinclude ("session_set_save_handler.php"), Session_Start (), if (Isset ($_session["user")) {echo "Welcome". $_ session["User"];echo "<a href= ' index.php?login=0 ' > Logout </a>";} Else{echo "You are not logged in, please login first!" "echo" <a href= ' index.php ' > Login </a> ";}? >
Session_set_save_handler.php Custom session storage mechanism function file
<?php//Open Session function open () {global $con;//Use global variable $con=mysqli_connect ("localhost", "root", "123456", "MySQL") or Die ( "Database connection Failed!"); Mysqli_query ($con, "Set names UTF8"); return (true);} Close database function Close () {global $con; Mysqli_close ($con); return (true);} Read Session_datafunction read ($key) {global $con; $time =time ();//Do not read expired session$sql= "select Session_data from T_ Session where session_key= ' $key ' and session_time> $time "; $result =mysqli_query ($con, $sql) or Die (" Query failed! "); if (! $result) {//used to check for errors that occur in the re-database section, it is useful to printf ("Error:%s\n", Mysqli_error ($con));//%s is a string, which is the exit () in C;} $row =mysqli_fetch_array ($result);//or die () will terminate the program behind! if ($row!=false) {return ($row ["Session_data"]);} Else{return "";//re-emphasize if null value, be sure to return "" instead of false}}//store sessionfunction write ($key, $data) {global $con; $over _time=time () + 60;//Note Time () is timestamp, data type in MySQL is not available with Date,datetime,timestamp to store $sql= "select Session_data from T_session where session_ Key= ' $key ', $re =mysqli_query ($con, $sql), $result =mysqli_fetch_array ($re);//If the $result is false, the result is null, indicating that the database does not have a correspondingsession_id, then insert, if not empty, that even if there is an unexpired session_id, this should be updated if ($result ==false) {$sql = "insert into T_session (Session_key, Session_data,session_time) VALUES (' $key ', ' $data ', $over _time) ";//strings are quoted in single quotes, numbers are not added $result=mysqli_query ($con , $sql), if (! $result) {//To check for errors that occur in the re-database section, it is useful to printf ("Error:%s\n", Mysqli_error ($con));//%s is a string, which is the exit () in C;}} else{$sql = "Update t_session set session_key= ' $key ', session_data= ' $data ', session_time= $over _time where session_key= ' $key ' "; $result =mysqli_query ($con, $sql);} return ($result);} Clear the corresponding session data function destroy ($key) {global $con; $sql = "Delete from t_session where session_key= ' $key '"; $result = Mysqli_query ($con, $sql); return ($result);} Perform garbage collection function overdue ($expire _time) {//This parameter is automatically passed in, that is session.gc_maxlifetime maximum effective time, such as 1440s;global $con; $time = Time (); $sql = "Delete from t_session where session_time< $time"; $result =mysqli_query ($sql); return ($result);} Session_set_save_handler (' open ', ' close ', ' read ', ' write ', ' destroy ', ' overdue '); >
Related articles recommended:
How PHP uses Phpmailer to send mail (with code)
Summary of some of the functions commonly used in PHP (induction)