phphttpcurlserver-sideweb-analytics

Send HTTP request from PHP without waiting for response?


I want to have an HTTP GET request sent from PHP. Example:

http://tracker.example.com?product_number=5230&price=123.52

The idea is to do server-side web-analytics: Instead of sending tracking information from JavaScript to a server, the server sends tracking information directly to another server.

Requirements:

Ideas for solutions:

In a nutshell: What is the best solution to do generic server-side tracking/analytics from PHP.


Solution

  • Unfortunately PHP by definition is blocking. While this holds true for the majority of functions and operations you will normally be handling, the current scenario is different.

    The process which I like to call HTTP-Ping, requires that you only touch a specific URI, forcing the specific server to boot-strap it's internal logic. Some functions allow you to achieve something very similar to this HTTP-ping, by not waiting for a response.

    Take note that the process of pinging an url, is a two step process:

    1. Resolve the DNS
    2. Making the request

    While making the request should be rather fast once the DNS is resolved and the connection is made, there aren't many ways of making the DNS resolve faster.

    Some ways of doing an http-ping are:

    1. cURL, by setting CONNECTION_TIMEOUT to a low value
    2. fsockopen by closing immediately after writing
    3. stream_socket_client (same as fsockopen) and also adding STREAM_CLIENT_ASYNC_CONNECT

    While both cURL and fsockopen are both blocking while the DNS is being resolved. I have noticed that fsockopen is significantly faster, even in worst case scenarios.

    stream_socket_client on the other hand should fix the problem regarding DNS resolving and should be the optimal solution in this scenario, but I have not managed to get it to work.

    One final solution is to start another thread/process that does this for you. Making a system call for this should work, but also forking the current process should do that also. Unfortunately both are not really safe in applications where you can't control the environment on which PHP is running.

    System calls are more often than not blocked and pcntl is not enabled by default.