Hi Guys,

I am currently trying to write a bit of code that handles the sessions in a mysql database.

  • Setting the Data - Worknig Fine

  • Reading the Data - Clears the session data

I am having problems with reading the data back again. When i try this it clears the data stored in teh session.

Here is the code for my Session Class:

<?php

    /**
     * File         : session.lib..php
     * Project      : Sessions
     * Author       : AD
     * Description  : Sessions stored into the database
     * Version      : 1.0 - 27/07/2009 - Initial Creation
     **/

    class SessionManager 
    {

            var $life_time;

            function SessionManager() 
            {

                    // Read the maxlifetime setting from PHP
                    $this->life_time = get_cfg_var("session.gc_maxlifetime");

                    // Register this object as the session handler
                    session_set_save_handler( 
                                            array($this, "open"), 
                                            array($this, "close"),
                                            array($this, "read"),
                                            array($this, "write"),
                                            array($this, "destroy"),
                                            array($this, "gc")
                                            );

                    $this->sql = new Site_Sql;              // Initiates the sql class
            }

            function open($save_path, $session_name) 
            {
                    global $sess_save_path;

                    $sess_save_path = $save_path;

                    // Don't need to do anything. Just return TRUE.

                    return true;
            }

            function close() 
            {
                    return true;
            }

            function read( $id ) 
            {

                    // Set empty result
                    $data = '';

                    // Fetch session data from the selected database

                    $time = time();

                    $this->sql->Connect();

                    $_query = sprintf("SELECT session_data FROM tbl_sessions WHERE session_id='%s' AND expires > '%s'", mysql_escape_string($id), mysql_escape_string($time));

                    //debug
                    echo $_query;

                    $results = $this->sql->Query($_query);

                    $row_count = $results->FetchNUM();                          

                    if($row_count > 0) 
                    {
                            $row= $results->FetchRow();
                            $data = $row['session_data'];

                    }       

                    $this->sql->Close();

                    return $data;

            }

            function write( $id, $data ) 
            {

                    // Build query                
                    $time = time() + $this->life_time;

                    $this->sql->Connect();

                    $_query = sprintf("INSERT INTO tbl_sessions (session_id, session_data, expires) VALUES ('%s', '%s', '%s') ON DUPLICATE KEY UPDATE session_data='%s', expires='%s'", mysql_escape_string($id), mysql_escape_string($data), mysql_escape_string($time), mysql_escape_string($data), mysql_escape_string($time));

                     // Debug
                    echo $_query;

                    $results = $this->sql->Query($_query);

                    $this->sql->Close();

                    return TRUE;
            }

            function destroy( $id ) 
            {

                    // Build query
                    $newid = mysql_real_escape_string($id);

                    $this->sql->Connect();

                    $_query = sprintf("DELETE FROM tbl_sessions WHERE session_id='%s'", mysql_escape_string($id));

                    // debug
                    echo $_query;

                    $results = $this->sql->Query($_query);

                    $this->sql->Close();

                    return TRUE;
            }

            function gc() 
            {

                    // Garbage Collection

                    $this->sql->Connect();

                    $_query = sprintf("DELETE FROM tbl_sessions WHERE expires < UNIX_TIMESTAMP()");

                    //debug
                    echo $_query;

                    $results = $this->sql->Query($_query);

                    $this->sql->Close();

                    // Always return TRUE
                    return true;
            }
    }

?>

and here is the code to set the session:


<?php  

echo "Sessions<br><br>";

echo "Creating Session: info...";



$SessionManager= new SessionManager;
session_start();

$_SESSION['info'] = "This is a variable in a session";

echo "...Done<br><br>";

echo "Click <a href=\"view.php\">here</a> to view the session<br><br>";

echo "Debug:<br><br>";


session_write_close();

?>

and the code for viewing the session:


<?php  

echo "Sessions<br><br>";

$SessionManager= new SessionManager;
session_start();

echo "Session Name: info<br>";
echo "Session Data: " . $_SESSION['infooo'] . "<br><br>";

echo "Click <a href=\"del.php\">here</a> to delete the session<br><br>";

echo "Debug:<br><br>";


?>

I hope someone can help me with this as its driving me up the wall!

Thankyou in advance.

Tony

    Could it simply be that you misspelled "info" as "infooo" in the last piece of code you posted?

      Haha, nope, i was doing some testing, must have forgotten to change it back, still having the same problems.

      Tony

        Hang on; what exactly is the criterion that gc() uses to decide if a session is old enough to be deleted?

          Weedpacket;10923122 wrote:

          Hang on; what exactly is the criterion that gc() uses to decide if a session is old enough to be deleted?

          Ooh...good catch. It looks like gc() would be deleting any data that wasn't saved less than a second ago.

            Hi Guys,

            Thanks for all of your efforts on this...

            GC isnt the problem, have commented it all out, but the session data is being removed from the db.

            mysql> select * from tbl_sessions;
            +----------------------------+----------------------------------------------+------------+
            | session_id                   | session_data                                    | expires    |
            +----------------------------+----------------------------------------------+------------+
            | XXXXXXXXXXXXXXXXX | info|s:31:"This is a variable in a session"; | 1248763183 | 
            +----------------------------+----------------------------------------------+------------+
            1 row in set (0.00 sec)
            

            i then go to the view page, and for some reason it runs the write functions because i get this output for the sql query:

            INSERT INTO tbl_sessions (session_id, session_data, expires) VALUES ('XXXXXXXXXXXXXXXXX', '', '1248763189') ON DUPLICATE KEY UPDATE session_data='', expires='1248763189'
            

            As you can see the session_data field is empty, but i dont know why, is my sql query wrong?

            after that the database looks like this:

            mysql> select * from tbl_sessions;
            +----------------------------+----------------------------------------------+------------+
            | session_id                   | session_data                                    | expires    |
            +----------------------------+----------------------------------------------+------------+
            | XXXXXXXXXXXXXXXXX |                                                           | 1248763183 | 
            +----------------------------+----------------------------------------------+------------+
            1 row in set (0.00 sec)
            

              Hi Guys,

              Iv now found the problem, when the read is done its not returning a value, because i have the wrong array in there, it should read row[0] rather than row['session_data'].

              ALL FIXED AND WORKING 🙂

              Thanks for everyones help.

              Kind Regards

              Tony

                Glad you found the problem, even if we didn't.

                Don't forget to mark this thread "resolved" (if it is) via the "Thread Tools" link near the top.

                  You might have a look at my custom session handler - as an inspiration if it helps, or if you find any flaws - I'm happy about any code review that I can get...or....simply use it if you like it.

                  http://code.google.com/p/pagebricks/

                  Bjom

                    Write a Reply...