Having read an article on custom sessions stored in a database, I decided to rewrite the class and build it into a site framework I was working on. All went well until I started using a header() redirect on the login form, When the redirect completed I frequently received this message:
Duplicate entry '**ID_REMOVED**' for key 1
Warning: Unknown(): A session is active. You cannot change the session module's ini settings at this time. in Unknown on line 0
This also started appearing if a page was refreshed quickly. Thinking it was a configuration problem I started researching and contacted my hosting company
The class function for writing the session looked like this
<?
/* Write new data to database */
function _write($ses_id, $data) {
$session_sql = "UPDATE " . $this->ses_table
. " SET ses_time='" . time()
. "', ses_value='$data' WHERE ses_id='$ses_id'";
$session_res = @mysql_query ($session_sql, $this->dblink) or die (mysql_error());
if (!$session_res) {
return FALSE;
}
if (mysql_affected_rows ()) {
return TRUE;
}
The problem turned out to be within this function itself rather than the configuration
The problem stemmed from the way the return from UPDATE is handled and the scripts reliance on the mysql_affected_rows() command
If the UPDATE command is executed on a record and no values are altered the command exits with a value of 0 meaning that the result of mysql_affected_rows() is false
This occurs on redirects and fast refreshes because the time value hasn't changed so no values are altered in the row, mysql_affected_rows() is false and the function continues as no condition is met to return a value... the following INSERT then causes the problem
The solution was do execute a simple SELECT to get the number of rows for the session ID and if mysql_affected_rows() evaluated to false but the number of records is 1 return true
I hope this helps someone as it took me a while to figure this out