Search code examples
phpbackground-process

Does this block the rendering of my page?


At the beginning of the PHP that generates all the pages of my site is like

log_visitor_info(
    $_SERVER['REMOTE_ADDR'],
    $_SERVER['REQUEST_URI'],
    $_SERVER['HTTP_REFERER'],
    $_SERVER['HTTP_USER_AGENT']
);

which calls the function

function log_visitor_info ( $ip, $pgurl, $refurl, $aginfo )
{
    global $wpdb, $ipsToIgnore; 
    if (!in_array($ip, $ipsToIgnore)) {
        $wpdb->insert('wp_nas_visits',  array(
            'ip'=>$ip,
            'refurl'=>$refurl,
            'pgurl'=>$pgurl,
            'aginfo'=>$aginfo
        ));
    }
}

where the $wpdb->insert is inserting something to the database. Because I don't need any of this info anywhere else in the page, I would prefer if it were possible to execute log_visitor_info asynchronously or "in the background", if you will. I think it's slowing down my page loads. Is there some way that I can put log_visitor_info on my server's queue that executes separately (if such a thing even exists ...) ? I have Windows Server 2012.


Solution

  • Not tested and I'm not a WordPress guy or fan, but should be adaptable if you want to use AJAX. First, create a PHP page (logger.php) and add the following:

    //include files needed to instantiate $wpdb
    
    $ipsToIgnore  = unserialize($argv[1]);
    $dataToInsert = unserialize($argv[2]);
    
    if (!in_array($dataToInsert['ip'], $ipsToIgnore)) $wpdb->insert('wp_nas_visits', $dataToInsert);
    

    Second, in the beginning of the PHP that generates all the pages of your site replace your function and function call with:

    $ips  = escapeshellarg(serialize($ipsToIgnore));
    $args = escapeshellarg(serialize(array('ip'     => $_SERVER['REMOTE_ADDR'],
                                           'pgurl'  => $_SERVER['REQUEST_URI'],
                                           'refurl' => $_SERVER['HTTP_REFERER'],
                                           'aginfo' => $_SERVER['HTTP_USER_AGENT'])));
    
    pclose(popen("start /B /path/to/php.exe /path/to/logger.php $ips $args", "r"));
    

    You may need to escapeshellarg() the path to php.exe and the path to logger.php as well, especially if they have spaces in them.