3

I want to register all the visits to a certain post in a Wordpress blog. The collected data is sent to an external server where I gather the information of this blog and other sources.

Until now, my way of solving this problem was using the hook wp_footer, adding an asynchronous JSONP call to the remote server. But this way adds a little overhead to the generated HTML, and depends if the user has enabled javascript.

Now, I'm trying to do the same but making the external call through the php code, using curl or any similar library. The problem here is adding lag to the page generation time, that can penalize the user experience. Is there any good way of doing this after the content is sent and the HTTP connection closed? Would be the Wordpress hook shutdown valid?

henrywright
  • 10,070
  • 23
  • 89
  • 150
Javier Marín
  • 2,166
  • 3
  • 21
  • 40
  • 1
    `shutdown` is indeed the very last wp hook that fires, that is: just before PHP shuts down execution. – diggy Apr 20 '13 at 13:40
  • 1
    like @diggy commented , `shutdown` is the last action, but you could also always do it the other way around, meaning to register the views inside wordpress, and then query it from the remote server . if the remote server is a third party , you could , like you said, send it through cron regardless of the actual page requests while querying this data collected while users access. – Obmerk Kronen Apr 21 '13 at 03:42

1 Answers1

2

This is what is working for me. Note that PHP has a native shutdown function if you don't want to be dependent on the WordPress configuration. From sending-server.com you could do something like this:

function do_php_shutdown_function(){
    //do your request here
    $param1 = urlencode($param1);
    $param2 = urlencode($param2);
    $request = "http://external-server.com/script.php?param1={$param1}&param2={$param2}";
    get_headers($request);
}
register_shutdown_function( 'do_php_shutdown_function');

In script.php on external-server.com you would have something like:

header("Access-Control-Allow-Origin: http://sending-server.com");
header("HTTP/1.0 204 No Content");
$param1 = urldecode($_GET['param1']);
$param2 = urldecode($_GET['param2']);
//do stuff

The header("HTTP/1.0 204 No Content"); should immediately close the connection yet the script will continue to execute. For more info see: Send HTTP request from PHP without waiting for response?

Community
  • 1
  • 1
i_a
  • 2,735
  • 1
  • 22
  • 21