PHP异步执行

1.采用fsockopen方式

function asyncGet($url)
{
    $parts = parse_url($url);
    $fp = fsockopen( $parts['host'],isset($parts['port']) ? $parts['port'] : 80,$errno, $errstr, 3);
    $out = 'GET ' . $parts['path'].'?'.$parts['query'] . " HTTP/1.1\r\nHost: " . $parts['host'] . "\r\nConnection: Close\r\n\r\n";
    fwrite($fp, $out);
    //usleep(10000);
    fclose($fp);
}

2.采用curl方式,此方式最少要等待一秒钟.

function asyncCurl($url)
{
$ch = curl_init(); 
$curl_opt = array(CURLOPT_URL=>$url,CURLOPT_TIMEOUT=>1,);
curl_setopt_array($ch, $curl_opt);
curl_exec($ch);
curl_close($ch);
}

3. fastcgi_finish_request方式,但fastcgi_finish_request太过局限性

故整合了一下函数,最终理想方式

function async($url)
{
	if(function_exists('fastcgi_finish_request'))
	{
		fastcgi_finish_request();
		file_get_contents($url);
	}
	else if (function_exists('fsockopen'))
	{
		$parts = parse_url($url);
    	$fp = fsockopen( $parts['host'],isset($parts['port']) ? $parts['port'] : 80,$errno, $errstr, 3);
    	$out = 'GET ' . $parts['path'].'?'.$parts['query'] . " HTTP/1.1\r\nHost: " . $parts['host'] . "\r\nConnection: Close\r\n\r\n";
    	fwrite($fp, $out);
    	//usleep(10000);
    	fclose($fp);
	}
	else
	{
		$ch = curl_init(); 
		$curl_opt = array(CURLOPT_URL=>$url,CURLOPT_TIMEOUT=>1,);
		curl_setopt_array($ch, $curl_opt);
		curl_exec($ch);
		curl_close($ch);
	}

}

 

 

你可能感兴趣的:(PHP异步执行)