PHP Database saves session sessions

Source: Internet
Author: User
Tags define session php session php database sprintf
This article is about the PHP database to save session sessions, now share to everyone, you can also give a friend need a reference, we take a look at it


Objective:


By default, PHP stores all session data in a text file on the server, which is usually stored in a temporary directory on the server.

So why do we keep session sessions in the database?

    1. The main reason: improve the security of the system. On a shared server, when no special settings are made, all site sites use the same temporary directory, which means that dozens of programs read and write files in the same location. Not only is the speed down, but people are also likely to steal user data from my site.

    2. Saving session data to a database also makes it easier to search for more information about a Web site session, and we can query the number of active sessions (as well as the amount of users online) and also back up session data.

    3. If my site is running on multiple servers at the same time, a user may send multiple requests to different servers during a session, but if the session data is saved on one server, the other servers will not be able to use the session data. If one of my servers is just the role of a database, is it not convenient for you to have the session data fully insured in the database?

More understanding of the PHP session can refer to this blog to thoroughly understand the session mechanism of PHP

1. Create a session table

Since the session data is stored on the server, and the client is holding an index (SessionID), the index corresponds to a session data on the server. So the table must contain two fields that are ID, data, and the session will have an expiration date, so there is a field here that is last_accessed, and here I have the table built under the test database:

CREATE TABLE sessions (    ID CHAR (+) NOT NULL,    data TEXT,    last_accessed TIMESTAMP not NULL,    PRIMARY KEY (ID ));

PS: If a program needs to save a large amount of data in a session, the data field may need to be defined as Mediumtext or longtext type.

2. Define session functions:

Here we have two main steps:

    1. Define functions that interact with the database

    2. Enable PHP to use these custom functions

In the second step, it is done by calling the function Session_set_save_handler (), which requires 6 parameters, namely open (Start session), close (closed session), read (read session), write (write session), destroy (Destruction session), clean (garbage collection).

We create a new PHP file sessions.inc.php with the following code:

&LT;?PHP$SDBC = null;      database connection handle, which in the following function makes it a global variable//start session function Open_session () {Global $sdbc;     Use global $sdbc $SDBC = mysqli_connect (' localhost ', ' root ', ' lsgogroup ', ' test ');    Database Test if (! $sdbc) {return false; } return true;    Close Session function Close_session () {Global $sdbc; Return Mysqli_close ($SDBC);}    Read session data function Read_session ($SID) {global $sdbc;    $sql = sprintf ("Select data from Sessions WHERE id= '%s '", Mysqli_real_escape_string ($SDBC, $sid));    $res = Mysqli_query ($sdbc, $sql);        if (mysqli_num_rows ($res) = = 1) {list ($data) = Mysqli_fetch_array ($res, mysqli_num);    return $data;    } else {return ';    }}//Write membership session data function Write_session ($sid, $data) {global $sdbc; $sql = sprintf ("INSERT into sessions (id,data,last_accessed) VALUES ('%s ', '%s ', '%s ')", Mysqli_real_escape_string ($SDBC    , $sid), mysqli_real_escape_string ($sdbc, $data), date ("Y-m-d h:i:s", Time ()));    $res = Mysqli_query ($sdbc, $sql);    if (! $res) {    return false; } return true;    Destroys session data function destroy_session ($SID) {global $sdbc;    $sql = sprintf ("DELETE from sessions where id= '%s '", Mysqli_real_escape_string ($SDBC, $sid));    $res = Mysqli_query ($sdbc, $sql);    $_session = Array ();    if (!mysqli_affected_rows ($sdbc) = = 0) {return false; } return true;    Perform garbage collection (delete old session data) function Clean_session ($expire) {global $sdbc;    $sql = sprintf ("DELETE from Sessions WHERE Date_add (Last_accessed,interval%d SECOND) <now ()", (int) $expire);    $res = Mysqli_query ($sdbc, $sql);    if (! $res) {return false; } return true; Tell PHP to use the session handler function Session_set_save_handler (' open_session ', ' close_session ', ' read_session ', ' write_session ', ' Destroy ' _session ', ' clean_session ');//Start a session, the function must be called after the Session_set_save_handler () function, or the function we define will not work. Session_Start ()///Because the file is included in the PHP file that needs to use the session, so no PHP end tag is added to it

Ps:

    1. Other functions must return a Boolean value outside of the read function, and the Read function must return a string.

    2. Each time the session starts, the "open" and "read" functions are called immediately. The garbage collection process can occur when the read function is called.

    3. When the script finishes, the Write function is called and then the close function, unless the session is destroyed, in which case the write function is not called. However, after the "close" function, the "destroy" function will be called.

    4. The. Session_set_save_handler () function parameter order cannot be changed because their one by one corresponds to open, close, read 、、、、

    5. The session data will eventually be stored in the database in the form of data serialization.

3. Use new Session Handler

Using a new session handler simply calls the Session_set_save_handler () function so that our custom function can be called automatically. Other operations on the session have not changed (how it used to be used now, our functions are automatically called in the background), including storing data in sessions, accessing saved session data, and destroying data.

Here, we create a new sessions.php file that creates session data when there is no session information and displays all session data, destroying session data when the user taps ' log out ' (logoff).

<?php// Introduce the sessions.inc.php file, i.e. the above code require (' sessions.inc.php '); ><!doctype html>

Parsing Session_write_close ():

As the name implies, the function is to write the membership session data, and then close session sessions, according to the truth that these two steps will be executed automatically after the script executes, why should we also explicitly call it? Because this involves the connection of the database!

As we know, PHP automatically shuts down all connections to the database after the script executes, while the session function attempts to write data to the database and close the connection. This can result in session data not being written to the database, and there are a lot of errors, such as write_session () and close_session () functions that are useful for connecting to the database.

To avoid the above problem, we call the Session_write_close () function before the script finishes executing, and he invokes the write function and the close function, and the database connection still exists!

PS: You should also call the Session_write_close () function before using the header () function to redirect the browser, if there is a database operation!

4. Test use

Open sessions.php in the browser, refresh the page, and then see if the database has any data added. Open the sessions.php in another browser and see if there is any additional data in the database .....

This blog is mainly for reference from the "deep understanding of PHP advanced skills, object-oriented and core technology", I hope to help everyone.

Related recommendations:

PHP Development Session principle and the use of detailed


Related Article

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.