I am experimenting with PHP session_set_save_handler and I would like to use a PDO connection to store session data.
I have this function as a callback for write actions:
function _write($id, $data) { logger('_WRITE ' . $id . ' ' . $data); try { $access = time(); $sql = 'REPLACE INTO sessions SET id=:id, access=:access, data=:data'; logger('This is the last line in this function that appears in the log.'); $stmt = $GLOBALS['db']->prepare($sql); logger('This never gets logged! :('); $stmt->bindParam(':id', $id, PDO::PARAM_STR); $stmt->bindParam(':access', $access, PDO::PARAM_INT); $stmt->bindParam(':data', $data, PDO::PARAM_STR); $stmt->execute(); $stmt->closeCursor(); return true; } catch (PDOException $e) { logger('This is never executed.'); logger($e->getTraceAsString()); } }
The first two log messages are always displayed, and the third immediately after $stmt = $GLOBALS['db']->prepare($sql) never gets into the log file and does not contain any traces of an exception.
The db session table remains empty.
The log message from the _close always present.
This is how I connect to the database:
$db = new PDO('mysql:host=' . DBHOST . ';dbname=' . DBNAME, DBUSER, DBPASS); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I have PHP 5.2.10.
I tried just running $GLOBALS['db']->exec($sql) with the "manually prepared" $sql content, but it still crashed. The request itself is right, I was able to execute it through the db console.
Edit:
After VolkerK identified the problem, I found this article that explains the cause of these strange phenomena. Perhaps this may be informative for others.
2nd edit:
The least painful, magical solution is that I had to add a function call below to the end of my front-control file (main index.php):
session_write_close();
php pdo session session-set-save-handler
Wabbitseason Apr 07 '10 at 20:56
source share