model-view-controllerzend-frameworkzend-dbzend-sessionzend-log

Zend_Session and Zend_Log _Db are both writing to the database twice for every page load


There are plenty of examples of similar problems littered around the web but none of their solutions seem to fix this particular variation. Any suggestions would be appreciated.

Usually this problem occurs because a rogue link is causing a request for a resources like a favicon or css file to hit the dispatcher more than once, thus causing multiple dispatch processes and therefore multiple rows in your database.

I have checked that all the links on this very simple example page do actually resolve to the resource to which they point.

The session handler is setup as follows:

Zend_Db_Table_Abstract::setDefaultAdapter($db);
Zend_Session::setSaveHandler(new 
            Zend_Session_SaveHandler_DbTable($config->session->toArray()));

The db logging is setup as follows:

$writer = new Zend_Log_Writer_Db($db, $config->log->tableName, 
            $config->log->columnMap->toArray());
$logger = new Zend_Log($writer);

Both objects are correctly setup and can read and write to and from the database. Only everything happens twice. If I put a test log message anywhere in the application it is written into the database twice. If I increment three variables with every call to the index action - one stored in the session, one passed around via a Zend_Registry object and another local to the indexAction - only the session variable is incremented by 2. The Apache access log shows the correct amount of requests being fired from the page load and all have good response codes of either 200 or 304 (unchanged).

I have tried disabling all head links. I have tried disabling the layout entirely. I have localised everything to the dispatcher and exited before dispatch is run.

In all cases the extra write/increment takes place. Any thoughts? Thanks in advance for any help.


Solution

  • I seem to have found and fixed the issue. Chrome (and possibly all Webkit browsers) issues an additional HEAD request on top of the GET which means the application is hit twice and anything session based will be triggered as a result of both requests. My temporary solution is to put the following code near the start of my index.php file.

    if ("HEAD" == $_SERVER['REQUEST_METHOD']) {
        exit;
    }
    

    I hope that helps anyone with the same issue.