Storing session information in a database

Source: Internet
Author: User
Tags mysql query php session

Most people who use PHP use cookies once they are applied to the session. Cookies are good but it also brings us some hidden dangers.

Hidden Danger One:

If the cookie for the client machine is invalidated by a virus, then the session information is equivalent to none.

Hidden Danger Two:

Session in PHP by default in the form of files stored in a temporary folder, for a small system, this can be done, but for a large and frequently accessed system, it is not a good way. Let's say the site has 1, 000 people to visit each day. There will be 30 000 temporary files in the temporary folder for the session after one months. Imagine it takes a lot of time for a computer to find a session_sid from 30 to 000. Therefore, in order to improve efficiency, using database to save session is a good way to solve this contradiction.

Session in PHP by default in the form of files stored in a temporary folder inside. You can change the way the session is saved by modifying the Session.save_handler settings of the php.ini file. The default is Session.save_handler = files, which must be modified to Session.save_handler = user, which becomes a custom method.

By completing this step, we can create our own user-level session save function (open, close, write, and so on), and then use the Session_set_save_handler function to register the Save function of the session that you created. Before using the Session_set_save_handler function, you must first configure the php.ini file, that is, session.save_hadler=user, otherwise the Session_set_save_handler function will not take effect.

If you want to use this session across the page, add your custom function and register with the Session_set_save_handler function in every script file that you use in session, so the best way is to make a separate file, Include in every script that will use session.

Directory structure

/samples/chap3/savesession session_save.php Registers the Save function of the session you created set_session_test.php Sess Ion set test Script get_session_test.php session display test script

table Structure of the database

Table 3-4 Save session (Db_session)

Column Name

Data type

Profile

Sesskey

CHAR (32)

Session keyword

Expiry

int (one) unsigned

Effective period

Value

Text

Session value


This example code

Program 3-5 session_save.php 1 <?php

This section uses the MySQL extension library for database operations, 2 rows to 5 rows to define global variables for database connections, data names, database user names, passwords, host names (IP addresses can also).

2 $GB _dbname= "samples";   3 $GB _dbuser= "root";   4 $GB _dbpass= "518"; 5 $gb _dbhostname= "localhost";

The variable is a $SESS_DBH database connection object that will be initialized in the Sess_open function.

6 $SESS _dbh= "";

Call the Get_cfg_var function to obtain the maximum lifetime of the session.

7 $SESS _life=get_cfg_var ("Session.gc_maxlifetime");

Defines the Sess_open function with two parameters to save the path $save_path (used when the file is saved), and the session name is $session_name. These two parameters, although not used within the function, must define the Sess_open function in this way. All session processing functions must follow the fixed definition shown here.

8 function Sess_open ($save _path, $session _name) {

Global is defined globally, but this global variable is not applied to the entire Web site, but is applied to the current page.
9 Global $GB _dbhostname, $GB _dbname, $GB _dbuser, $GB _dbpass, $SESS _dbh;

Establish a database connection and initialize the database connection object $SESS_DBH. There are two functions for establishing a database connection in the MySQL extension library, Mysql_pconnect is used to establish a persistent connection to the database, and the function mysql_connect is used to establish a non-persistent connection. An error message is displayed when a connection error occurs.

if (! $SESS _dbh=mysql_pconnect ($GB _dbhostname, $GB _dbuser, $GB _dbpass)) {One echo " <li>MYSQL Error: ". Mysql_error ()." <li>";   Die (); 13}

Specifies the object database, which is equivalent to executing "use database name;" 's command.

if (!mysql_select_db ($GB _dbname, $SESS _dbh)) {echo <li>MYSQL Error: ". Mysql_error ()." <li>";   Die ();   "Return true; 19}

Defines the close session method.

The function Sess_close () {return true; 22}

Read the session function, the parameter is the session keyword name (randomly generated garbled).

The function Sess_read ($key) {global $SESS _dbh, $SESS _life;

In terms of the session keyword, the session information from the table db_session is retrieved within the validity period.

$qry = "Select value from db_session where Sesskey = ' $key ' and expiry >". Time ();

The mysql_query function executes a MySQL query. The second parameter is a database connection, which is omitted using the last open connection.

$qid =mysql_query ($qry, $SESS _dbh);

Mysql_fetch_row obtains a row from the result set as an array of numbers. Calling Mysql_fetch_row () in turn returns the next row in the result set, or FALSE if there are no more rows. When successful, the result of this row is to place the value taken out in the variable $value.

The IF (list ($value) =mysql_fetch_row ($qid)) {return $value;   return false; 31}

Saves session information to the database.

The function Sess_write ($key, $val) {_DBH global $SESS, $SESS _life;

The duration of the session is the time after the current time plus the maximum validity period.

$expiry =time () + $SESS _life;   $value = $val;   $qry = "INSERT into db_session values (' $key ', $expiry, ' $value ')"; Panax Notoginseng $qid =mysql_query ($qry, $SESS _dbh);

Insert failure means that the session record is already in the database, and the session is updated.

if (! $qid) {$qry = "update db_session set expiry= $expiry, value= ' $value ' where sesskey= ' $key ' and ex Piry >". Time ();   $qid =mysql_query ($qry, $SESS _dbh);   $qid; 43}

Defines the Sess_destroy function that deletes session information, which is performed when the screen is closed.

The function Sess_destroy ($key) {global $SESS _dbh;   $qry = "Delete from db_session where Sesskey = ' $key '";   $qid =mysql_query ($qry, $SESS _dbh);   $qid; 49}

Defines a function sess_gc that automatically deletes expired session information.

The function sess_gc ($maxlifetime) {Wuyi global $SESS _dbh;   $qry = "Delete from db_session where expiry <". Time ();   $qid =mysql_query ($qry, $SESS _dbh);   The return mysql_affected_rows ($SESS _dbh); 55}

The Session_module_name function with no parameters is used to obtain the current session module.

Session_module_name ();

Registers a custom session function, including opening, closing, writing, and so on. Session_set_save_handler ("Sess_open", "Sess_close"), "
Sess_read "," Sess_write "," Sess_destroy "," sess_gc "); ?> program 3-6 set_session_test.php 1 <?php

Contains a custom session processing file. This file must be included in all pages that use custom session processing, which is how the database is saved.

2 include ("session_save.php");

Call the Session_Start function, and session processing begins.

3 session_start ();

Sets the session variable.

4 $_session[' message ']= ' Can I help you? ';   5 $_session[' message1 ']= "no,thanks";   6 $_session[' from ']= "Tom";   7 echo "<a href=\" Get_session_test.php\ "> Show session</a>";   8?> Program 3-7 get_session_test.php 1 <?php 2 include ("session_save.php"); 3 session_start ();

Displays the session variable.   4 echo $_session[' message '];   5 echo "<br>";   6 echo $_session[' Message1 '];   7 echo "<br>";   8 echo $_session[' from '];   9 $_session[' addmess ']= "Hello"; Ten?>

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.