Quantcast
Viewing latest article 3
Browse Latest Browse All 4

PHP Post an Asynchronous request

Sometimes I need to trigger an URL with some requests and I have been using cURL for this job. However I realized that if I make a lot of such requests it would slow down the original script because it’s going to wait for a response from the triggered URL. Since I don’t need that it would be helpful to just fire a request and ignore it. Here’s the code snippet I found:

function curl_post_async($url, $params)
{
    foreach ($params as $key => &$val) {
      if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key.'='.urlencode($val);
    }
    $post_string = implode('&', $post_params);

    $parts=parse_url($url);

    $fp = fsockopen($parts['host'],
        isset($parts['port'])?$parts['port']:80,
        $errno, $errstr, 30);

    pete_assert(($fp!=0), "Couldn't open a socket to ".$url." (".$errstr.")");

    $out = "POST ".$parts['path']." HTTP/1.1\r\n";
    $out.= "Host: ".$parts['host']."\r\n";
    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out.= "Content-Length: ".strlen($post_string)."\r\n";
    $out.= "Connection: Close\r\n\r\n";
    if (isset($post_string)) $out.= $post_string;

    fwrite($fp, $out);
    fclose($fp);
}

Source: http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html


Viewing latest article 3
Browse Latest Browse All 4

Trending Articles