天天看點

兩段代碼掌握php session

最近學習session,自己覺得可以通過這兩個方法更快的掌握session,通過代碼一可以更快的掌握session 6個階段的執行時機,代碼二是簡單實作了mysql存儲session,

希望對學友有幫助!

代碼一,session各階段運作時機

<?
/*
Session open (called by session_start( ))
Session close (called at page end)
Session read (called after session_start( ) )
Session write (called when session data is to be written)
Session destroy (called by session_destroy( ) )
Session garbage collect (called randomly)
*/
    function sess_open($sess_path, $sess_name) {
            print "Session opened.\n";
            print "Sess_path: $sess_path\n";
            print "Sess_name: $sess_name\n\n";
            return true;
    }
 
    function sess_close( ) {
            print "Session closed.\n";
            return true;
    }
 
    function sess_read($sess_id) {
            print "Session read.\n";
            print "Sess_ID: $sess_id\n";
            return '';
    }
 
    function sess_write($sess_id, $data) {
            print "Session value written.\n";
            print "Sess_ID: $sess_id\n";
            print "Data: $data\n\n";
            return true;
    }
 
    function sess_destroy($sess_id) {
            print "Session destroy called.\n";
            return true;
    }
 
    function sess_gc($sess_maxlifetime) {
            print "Session garbage collection called.\n";
            print "Sess_maxlifetime: $sess_maxlifetime\n";
            return true;
    }
 
    session_set_save_handler("sess_open", "sess_close", "sess_read",
                    "sess_write", "sess_destroy", "sess_gc");

    //實驗開始
    /*
        開啟session,這裡首先确認php.ini session.auto_start=0
        否則這裡是無效的,一般session.auto_start 預設是 0 
    */
    session_start( );
 
     /*
        這裡可以發現,session寫入檔案或資料庫是在整個檔案執行完之後,
        在檔案執行完之前$_SESSION是存在記憶體中的
     */
    $_SESSION['foo'] = "bar";
    echo $_SESSION['foo'];
    print "Some text\n";
    $_SESSION['baz'] = "wombat";
?>
           

代碼二,mysql存儲session簡單實作

<?php # Script 3.1 - db_sessions.inc.php

/* 
 *  This page creates the functional interface for 
 *  storing session data in a database.
 *  This page also starts the session.
 */

// Global variable used for the database 
// connections in all session functions:
$sdbc = NULL;

// Define the open_session() function:
// This function takes no arguments.
// This function should open the database connection.
// This function should return true.
function open_session() {
    global $sdbc;
    $sdbc = @mysqli_connect('localhost', 'root', 'root', 'session', '3306');
    if ($sdbc) {
        return true;
    } else {
        die('mysqli errorcode:'. mysqli_connect_errno() . '<br/> mysqli errormsg: '. mysqli_connect_error().'<br>'. debug_print_backtrace());
    }
} // End of open_session() function.
 
// Define the close_session() function:
// This function takes no arguments.
// This function closes the database connection.
// This function returns the closed status.
function close_session() {
    global $sdbc;
    
    return mysqli_close($sdbc);
} // End of close_session() function.

// Define the read_session() function:
// This function takes one argument: the session ID.
// This function retrieves the session data.
// This function returns the session data as a string.
function read_session($sid) {
    global $sdbc;

    // Query the database:
    $q = sprintf('SELECT data FROM sessions WHERE id="%s"', mysqli_real_escape_string($sdbc, $sid)); 
    $r = mysqli_query($sdbc, $q);
    
    // Retrieve the results:
    if (mysqli_num_rows($r) == 1) {
        list($data) = mysqli_fetch_array($r, MYSQLI_NUM);
        
        // Return the data:
        return $data;

    } else { // Return an empty string.
        return '';
    }
} // End of read_session() function.

// Define the write_session() function:
// This function takes two arguments: 
// the session ID and the session data.
function write_session($sid, $data) {
    global $sdbc;

    // Store in the database:
    $q = sprintf('REPLACE INTO sessions (id, data) VALUES ("%s", "%s")', mysqli_real_escape_string($sdbc, $sid), mysqli_real_escape_string($sdbc, $data)); 
    $r = mysqli_query($sdbc, $q);

	return true;
} // End of write_session() function.

// Define the destroy_session() function:
// This function takes one argument: the session ID.
function destroy_session($sid) {
    global $sdbc;

    // Delete from the database:
    $q = sprintf('DELETE FROM sessions WHERE id="%s"', mysqli_real_escape_string($sdbc, $sid)); 
    $r = mysqli_query($sdbc, $q);
    
    // Clear the $_SESSION array:
    $_SESSION = array();

    return true;
} // End of destroy_session() function.

// Define the clean_session() function:
// This function takes one argument: a value in seconds.
function clean_session($expire) {
    global $sdbc;

    // Delete old sessions:
    $q = sprintf('DELETE FROM sessions WHERE DATE_ADD(last_accessed, INTERVAL %d SECOND) < NOW()', (int) $expire); 
    $r = mysqli_query($sdbc, $q);

    return true;
} // End of clean_session() function.

# **************************** #
# ***** END OF FUNCTIONS ***** #
# **************************** #

// Declare the functions to use:
session_set_save_handler('open_session', 'close_session', 'read_session', 'write_session', 'destroy_session', 'clean_session');

// Make whatever other changes to the session settings, if you want.

// Start the session:
session_start();