PHP Custom Session Control---using file processing

Source: Internet
Author: User
Tags php session

The first three simple summary of the next session control and file operations, this is a talk about session control of the custom processing mode. Since we know the basic reading and writing of the file, and in the session control, it is also mentioned that the sessions can be saved to the cache or database, in fact, of course, will not be directly using PHP session processing mechanism, all users of the session information saved in a file, access to a large amount, Issues such as multiple information data, inability to share, and so on may arise, so we need to customize session control. Before implementing a custom session control, you need to know how PHP itself is doing session management. Here, the simple implementation of this is saved to a file in a custom directory, so the cache or database is obvious.

Let's start with a few commands, which will help us understand its mechanism. Open the PHP configuration file and find some sessions. The beginning of the command entry:

Session.save_handler: Its value by default is files, see its English explanation, if its value is files, then it is to use the PHP itself mechanism to process, its information will be saved to the place specified by Session.save_path, If you want to customize session processing, you need to assign users to it.

Session.save_path: In the win version of the PHP configuration file, it is commented out by default, that is, in the configuration file does not say its value is how much, but there must be a place to put the session data is not, win, this place is C:\Windows\Temp, You can find it in (below, if you have practiced the program stored by the session) with a Sess_ prefix, followed by a long string of length strings, no extension file, it is the default session data, It is stored in the serialized (and also the serialization) after the data (such as user|s:4: "Jack";, the user is the variable name, "Jack" is the variable value, "s" is the variable type string, the colon after the 4 for the length, the last semicolon to end the variable, which is just a simple numeric type, There are objects and so on that can also be serialized). About Save_path, he also has a number of configuration methods, such as digital grading, more convenient for large numbers of data file storage, specifically do not elaborate.

Figure out its handling and storage, in fact, it should come out such a problem: we usually do not move the session data, if it has been kept in storage, it will not fill the disk? Do you want to write a script to delete them? Fortunately, PHP provides the session's automatic recovery mechanism, which is garbage collection. Understand the recycling mechanism or need to look at the command entry.

SESSION.GC_PROBABILITY:GC is garbage collection recovery shorthand, meaning probability, possibility

Session.gc_divisor: The meaning is the divisor, these two should be combined to see, in the existing session file inside, for the expired, to gc_probability/gc_divisor the probability to choose one of the deletion, This will be done every time the session is initialized. So suppose Gc_divisor is 1000,gc_probability is 1, and at this time there are 1000 expired session files, then not all delete, but randomly pick one of the deletion, that is, the probability of 1/1000.

Session.gc_maxlifetime:session time, only the session file that exceeds this effective time will be included in the scope of the PHP garbage collection.

With this knowledge of preparation, the next step is to go to the custom process of the session.

Regardless of whether it is stored in memcache or database, or otherwise, the original principle is the same, PHP in processing session data using a function: Session_set_save_handler. The latest prototypes are:

BOOL Session_set_save_handler (callable $open, callable $close, callable $read, callable $write, callable $destroy, Callable $GC [, callable $create _id])

You can see that this function is going to call the callback function again. First of all, we know that from the beginning of the session to hang up, to session_start a session, to $_session inside write data to save session information, or read the information in the array, run out of destroy its data, so a few steps, In response to the names of these functions, it is sorta.

Open: It has two parameters---$save _path and $session_id, the parameters passed to it have shown that it is processing the path of the session data, it is actually through it to change the file storage directory, it can not be c:windows\temp. It creates a completely new session session_start, or start an existing session will be automatically called by PHP (Session_Start ()), and only return true to proceed with the next step.

Close: It has no arguments to close the current session and is automatically called when you close a session, or when you explicitly call another PHP function session_write_close.

READ: It requires a parameter, $session_id, to read the session information of the user with ID $session_id from the place where the session data is stored and return it for subsequent internal processing. It continues to be called when Session_Start () opens a session, or when the open function is called internally. Returns the current user session data written to $_session.

Write: It requires two parameters---$session _id and $session_data, it is obvious that the corresponding session information written to the user $session_id $session_data to the specified file. This session_data is the serialized data and returns true to proceed to the next step. It can be executed when the normal script is closed, but also when an intrinsic function session_write_close () call or an intrinsic function Session_register_shutdown call fails. Most obviously, when we assign a value to the $_session array, it is executed.

Destroy: It has a parameter $session_id, which is called at Session_destroy, to delete the session_id corresponding session information.

GC: parameter is $maxlifetime, for start garbage collector (start session or session_start is called) execution, seemingly start garbage collection is also be randomly called, wayward!

CREATE_SID: This callback function is optional and can not be written. It has no parameters and can be written when a new session ID is required, such as PHP and a function session_regenerate_id that regenerates the session ID.

In summary, Session_Start () executes open, read, and GC when the $_session array is assigned values, and later operations $_session do not invoke them, calling Session_write_ When the close intrinsic function is called, write and close are invoked.

======================================================================

So many words, that is, before start a session, we have to do is:

1, Session.save_handler change to user, restart Apache, or, use Ini_set temporarily modify the command;

2. Write the required callback function corresponding to the Session_set_save_handler function.

3. Redefine the Session_set_save_handler function, using the name of the callback function above;

4, code a session program, before each call to Session_Start (), make sure that this run the script when the above redefinition function can be called to.

The work of modifying the command has been done, first writing a script custom_session.php, customizing the Session_set_save_handler function.

<?php Ini_set ('Save_handler','Users');//using custom processing$session _save_path='g:/sessionfiles/';//Customizing a storage directory//session_start () will call itfunction Open ($save _path, $session _id) {echo'<br>call open.<br>'; Global$session _save_path; $save _path= $session _save_path;//Modify the directory where session data is stored    return true; }        //called when the session is destroyed or called Session_write_closefunction Close () {echo'<br>call close.<br>'; return true; }        //reads session data and returnsfunction Read ($session _id) {echo'<br>call read.<br>'; Global$session _save_path; $filename= $session _save_path.'sessionid_'. $session _id.'. txt'; $content=@file_get_contents ($filename); return$content; }        //writes data to the application user (as determined by the session ID) to the filefunction Write ($session _id, $session _data) {echo'<br>call write.<br>'; Global$session _save_path; $filename= $session _save_path.'sessionid_'. $session _id.'. txt';//Customize a file name, preferably with a certain rule            if($handle = @fopen ($filename,'w+')) ==true) {$bytes=@file_put_contents ($filename, $session _data); return$bytes; }    Else{            return false; }        return false; }        //execute when calling Session_destroy, delete correspondingfunction Destroy ($session _id) {echo'<br>call destroy.<br>'; Global$session _save_path; $filename= $session _save_path.'sessionid_'. $session _id.'. txt'; return@unlink ($filename);//Delete files/data    }    //Garbage CollectionFunction GC (int$maxlifetime) {echo'<br>call gc.<br>'; Global$session _save_path; $files= Glob ($session _save_path.'sessionid_*'); foreach($files as$filename) {        if(Filemtime ($filename) + $maxlifetime <Time ())        {@unlink ($filename); }        }    return true; } session_set_save_handler ('Open','Close','Read','Write','Destroy','GC');

Then, write a simple user login to verify the script to try, the former part is the PHP verification operation, behind the page, but also include the previous custom processing mode script

<?PHP//change session to custom processing    include' Custom_session.php '; Echo' <br>before call Session_Start fun.<br> '; Session_Start();//session is turned on, and if it is on, it returns the session ID that already exists.          Echo' Session ID: '.session_id().‘ <br> ';//Output Session ID          if(!Empty($_post["Sub"]))//If you click Sign in    {        include"Conn.inc.php";//connecting to a database        $sql= "SELECT id from Sessionuser where username= '".$_post["User"]. "' and password= ' ".MD5($_post["Pass"]). "'"; //echo ' sql=> '. $sql. ' <br> ';        $result=$mysqli->query ($sql); if($result->num_rows > 0)       {           $assRow=$result-Fetch_assoc (); $_session["User"] =$_post["User"];//Storing session data           $_session["UID"] =$assRow["id"]; $_session["islogin"] = 1; }else{Echo"<br>wrong username or password, please relogin.";
} } ?>Echo' <br>script end.<br> ';?>

The results are as follows:

Before Session_Start () made the mark "before Call Session_Start fun.", at the end of the script was marked "script End", very clearly seen in the session_start () The call then calls open and read, and automatically calls write and close before the script automatically ends, but it does not destroy the session information, but automatically writes the session information at the end of the script, close closes the current conversation.

Then log out and destroy the session information:

<?PHP//Customizing session Handling    include' Custom_session.php '; Echo' <br>before call Session_Start fun.<br> '; Session_Start(); $_session=Array();//Delete all variables stored in $_session at once    if(isset($_cookie[Session_name()] ) )    {        Setcookie(Session_name(), ‘‘, Time()-3600, '/'); }    Echo' <br>before call Session_destroy fun.<br> '; Session_destroy();? ><br><a href= "login.php" >relogin</a><br><?phpEcho' <br>script end.<br> ';?>

Similarly, Mark "before Call Session_destroy fun" at the end of the script, marking "Session_Start" in the calling Session_destroy.

It can be seen that after calling Session_Start, the open and read functions are followed, and then the program is destroyed, and then the destroy and close functions are called after the call to Session_destroy, and then the end of the script ends. Further proof of the invocation of these functions.

Finally, is the session data saved to the place we specified? Look↓ didn't run.

Of course, you can also mark more carefully, to see the truth ~ Note end

PHP Custom Session Control---using file processing

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.