How to make asynchronous POST with PHP

How to make asynchronous POST with PHP

  • @Tsartsaris

    Posted on 2014-06-04

    ‚ÄčThere are several ways to make a async call with PHP. I will describe in this post how to Asynchronous POST a PHP Array to a php script with cURL making a "fire and forget" call, meaning that we will post the data and we will not wait for a result. In our example, we will post the $_SERVER array to a script in another page without waiting to see what the script is doing. We are going to need two files, the first will be named async.php and the second will be the handler.php which will handle the array we will post. Let me give you the code at this point and will talk about it later on.  the async.php file


    $fields = $_SERVER;

    $curl_options = array(
    CURLOPT_URL => "",
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => http_build_query( $fields ),

    $curl = curl_init();
    curl_setopt_array( $curl, $curl_options );
    $result = curl_exec( $curl );
    curl_close( $curl );
    echo "I am echoing out since I am not waiting for a result";

    the handler.php file


    header("Connection: close");
    header("Content-Length: " . ob_get_length());


    $user_agent = $_POST['HTTP_USER_AGENT'];

    $visitor_ip = $_POST['REMOTE_ADDR'];

    $tomail = "User Agent :".$user_agent."\r\nVisitor IP : ".$visitor_ip;
    mail('', 'curl test', $tomail);


        In the async.php file we prepare to POST the array with cURL. Assigning the $_SERVER array to $fields, which will be used in the cURL options. With http_build_query we take the $fields array and we create a URL-encoded query string to pass to cURL. The critical part in the cURL options array is the CURLOPT_TIMEOUT that we set to 1. What we do is posting the data and after one (1) second we close the connection not waiting for an answer. Then we echoing something just to be sure the connection is closed. 

        In the handler.php first seven (7) lines, until flush(); are for the connection handling. In the most simple way I can describe it is that we say to php "Even thought the connection with the one who posted the data lost or closed, go on to complete the job". Read more about Connection handling. After that just for the scientific evidence we tell the script to sleep for 5 seconds and then sent an email with some data. 

        So if we go and visit the async.php it will post the array with curl, close the connection with the handler.php after 1 second and then echo our text. The handler.php will deal with the closed connection as it never happened, will wait for 5 seconds and then it will email us the data we want. Remember to change the mail address with yours please.



Social Me!

Twitter Logo LinkedIn Logo Google+ Logo Tumblr Logo