msphpsql icon indicating copy to clipboard operation
msphpsql copied to clipboard

When using PHP Session handlers -> Mysterious bug

Open v-mabarw opened this issue 12 years ago • 1 comments

Hi.

PHP spits out this if you try to connect to a SQL Server 2005 server in session handling functions:
PHP Fatal error: sqlsrv_errors contains an invalid type in (path)/session.php on line 29

Line 29 is wherre sqlsrv_connect is

When I use that OUTSIDE the session handling functions, it works fine, there are no problems what so ever.

Code to reproduce the problem:
function sess_open($save_path, $session_name)
{

return true;

}

function sess_close()
{

return true;

}

function sess_read($id)
{

return '';

}

function sess_write($id, $sess_data)
{

$connectionInfo = array( 
    "UID"=>"MyUser",
    "PWD"=>"MyPassword",
    "Database"=>"MyDB" 
);

$conn = sqlsrv_connect("mySQLServer", $connectionInfo);

sqlsrv_query($conn,"SELECT 1 FROM sessions");

return true;

}

function sess_destroy($id)
{

return true;

}

function sess_gc($maxlifetime)
{

return true;

}

session_set_save_handler('sess_open', 'sess_close', 'sess_read', 'sess_write', 'sess_destroy', 'sess_gc');
session_start();

Work Item Details

Original CodePlex Issue: Issue 15199 Status: Closed Reason Closed: Unassigned Assigned to: Unassigned Reported on: Dec 5, 2009 at 8:47 AM Reported by: Auro Updated on: Oct 17, 2011 at 8:42 PM Updated by: jguerin Closed on: Oct 17, 2011 at 8:42 PM

v-mabarw avatar Jul 29 '14 22:07 v-mabarw

On 2010-04-21 21:28:47 UTC, robertjohnson commented:

Read the PHP warning in the documentation at http://php.net/manual/en/function.session-set-save-handler.php. Although the sqlsrv connection resource does not appear to be an object, it is destroyed at the object level. The solution is to put your session handlers in a class, and in the destructor, call 'session_write_close();'.

Here's my version:

function SetSessionHandler() { static $s_sess; $s_sess = new CSession(); session_set_save_handler( array($s_sess, 'sess_open'), array($s_sess, 'sess_close'), array($s_sess, 'sess_read'), array($s_sess, 'sess_write'), array($s_sess, 'sess_destroy'), array($s_sess, 'sess_gc')); }

The class:

class CSession { public $conn;

function __destruct() { session_write_close(); // IMPORTANT! }

function sess_open($save_path, $session_name) { this->conn = sqlsrv_connect(...); // .... }

function sess_close() { } function sess_read() { } /// add all the session functions. }

v-mabarw avatar Jul 29 '14 22:07 v-mabarw