欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

How to make Asynchronous http calls using PHP?

shiping1 的头像
<?php
//Calling http url asynchronously with parameters
async_call('http://localhost/php/test1.php';, 'test=something&category=somecategory');

/*
Make Async http call
$url = Url to make Async call e.g. http://www.somesite.com or http://www.somesite.com:80
$paramstring = Parameter string in the format of querystring with name=value separated by "&" e.g.: name1=value1&name2=value2
$method = "GET" or "POST"
$timeout = Timeout in seconds. Default 30 seconds
$returnresponse = true/false. Default false. If true, waits for response and return back response data.
*/
function async_call($url, $paramstring, $method='get', $timeout='30', $returnresponse=false) 
{
	$method = strtoupper($method);
	$urlParts=parse_url($url);      
	$fp = fsockopen($urlParts['host'],         
			isset($urlParts['port'])?$urlParts['port']:80,         
			$errno, $errstr, $timeout);
	
	//If method="GET", add querystring parameters
	if ($method='GET')
		$urlParts['path'] .= '?'.$paramstring;
	
	$out = "$method ".$urlParts['path']." HTTP/1.1\r\n";     
	$out.= "Host: ".$urlParts['host']."\r\n";
	$out.= "Connection: Close\r\n";
	
	//If method="POST", add post parameters in http request body
	if ($method='POST')
	{
		$out.= "Content-Type: application/x-www-form-urlencoded\r\n";     
		$out.= "Content-Length: ".strlen($paramstring)."\r\n\r\n";
		$out.= $paramstring;      
	}
	
	fwrite($fp, $out);     
	
	//Wait for response and return back response only if $returnresponse=true
	if ($returnresponse)
	{
		echo stream_get_contents($fp);
	}
	
	fclose($fp); 
}
?>

来自  http://codeissue.com/issues/i64e175d21ea182/how-to-make-asynchronous-http-calls-using-php


/**
 * Posts to a page in the background.
 *
 * Specifically what this does is open a connection, write the data, and then
 * immediately close the connection.
 *
 * Example usage: background_post(current_full_url(), array('background' => 1));
 *
 * Pages that expect to be called in the background should usually call
 * ignore_user_abort(true) as soon as possible to avoid being terminated early
 * when the connection is closed.
 *
 * @param $url
 *   The URL to call in the background.
 * @param $data
 *   (Optional) An associative array of data to POST.
 * @param $debug
 *   (Optional) If TRUE, the request is executed synchronously and an array of
 *   relevant information is returned on success (instead of returning TRUE).
 *
 * @return
 *   TRUE if the request succeeded or an error string if it failed.
 */
function background_post($url, $data = array(), $debug = FALSE) {
  $parts = parse_url($url);
  $host = $parts['host'];
  if (isset($parts['port'])) {
    $port = $parts['port'];
  }
  else {
    $port = $parts['scheme'] == 'https' ? 443 : 80;
  }
  if ($port == 443) {
    $host = 'ssl://' . $host;
  }
 
  $data_params = array();
  foreach ($data as $k => $v) {
    $data_params[] = urlencode($k) . '=' . urlencode($v);
  }
  $data_str = implode('&', $data_params);
 
  $fp = fsockopen(
    $host,
    $port,
    $errno,
    $errstr,
    3
  );
 
  if (!$fp) {
    return "Error $errno: $errstr";
  }
  else {
    $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";
    if (!empty($data_str)) {
      $out .= "Content-Length: " . strlen($data_str) . "\r\n";
    }
    $out .= "Connection: Close\r\n\r\n";
    if (!empty($data_str)) {
      $out .= $data_str;
    }
    fwrite($fp, $out);
    if ($debug) {
      $contents = '';
      while (!feof($fp)) {
        $contents .= fgets($fp, 128);
      }
    }
    fclose($fp);
    if (!$debug) {
      return TRUE;
    }
    else {
      return array(
        'url' => $parts,
        'hostname' => $host,
        'port' => $port,
        'request' => $out,
        'result' => $contents,
      );
    }
  }
}

Example usage:

ignore_user_abort(TRUE);
 
/**
 * Your time-consuming operations go here.
 */
function perform_heavy_calculations() {}
 
/**
 * Returns the current full URL.
 *
 * Example response: https://example.com/index.php
 */
function current_full_url() {
  return (
    isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on'
    ? 'https' : 'http'
  ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
 
if (empty($_POST['background'])) {
  echo file_get_contents('cache.html');
  background_post(current_full_url(), array('background' => TRUE));
  die();
}
 
$results = perform_heavy_calculations();
 
file_put_contents('cache.html', $results);



来自  http://www.isaacsukin.com/news/2012/11/asynchronous-requests-php

普通分类: