PHP implements sending asynchronous request method

小云云
Release: 2023-03-22 11:42:02
Original
11769 people have browsed it

This article mainly shares with you the method of sending asynchronous requests in PHP. Recently, I have encountered problems that require the use of PHP asynchronous requests many times at work, so I searched for relevant information on the Internet. After many tests and modifications, two generally feasible solutions have been summarized:

1. Solution 1: Use CURL, but CUROPT_TIMEOUT must be set to 1.

function _curl($url, $data=null, $timeout=0, $isProxy=false){
    $curl = curl_init();
    if($isProxy){   //是否设置代理
        $proxy = "127.0.0.1";   //代理IP
        $proxyport = "8001";   //代理端口
        curl_setopt($curl, CURLOPT_PROXY, $proxy.":".$proxyport);
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if(!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                "cache-control: no-cache",
                "content-type: application/json",)
        );
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    if ($timeout > 0) { //超时时间秒
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    }
    $output = curl_exec($curl);
    $error = curl_errno($curl);
    curl_close($curl);
    if($error){
        return false;
    }
    return $output;
}
_curl('http://localhost/index.php',null,1);
Copy after login


2. Option 2: Use fsockopen, but you need to spell out the HTTP header part yourself

function _fsockopen($url,$post_data=array(),$cookie=array()){
	$url_arr = parse_url($url);
	$port = isset($url_arr['port'])?$url_arr['port']:80;
	if($url_arr['scheme'] == 'https'){
		$url_arr['host'] = 'ssl://'.$url_arr['host'];
	}
	$fp = fsockopen($url_arr['host'],$port,$errno,$errstr,30);
	if(!$fp) return false;
	$getPath = isset($url_arr['path'])?$url_arr['path']:'/index.php';
	$getPath .= isset($url_arr['query'])?'?'.$url_arr['query']:'';
	$method = 'GET';  //默认get方式
	if(!empty($post_data)) $method = 'POST';
	$header = "$method  $getPath  HTTP/1.1\r\n";
	$header .= "Host: ".$url_arr['host']."\r\n";
	if(!empty($cookie)){  //传递cookie信息
		$_cookie = strval(NULL);
		foreach($cookie AS $k=>$v){
			$_cookie .= $k."=".$v.";";
		}
		$cookie_str = "Cookie:".base64_encode($_cookie)."\r\n";
		$header .= $cookie_str;
	}
	if(!empty($post_data)){  //传递post数据
		$_post = array();
		foreach($post_data AS $_k=>$_v){
			$_post[] = $_k."=".urlencode($_v);
		}
		$_post = implode('&', $_post);
		$post_str = "Content-Type:application/x-www-form-urlencoded; charset=UTF-8\r\n";
		$post_str .= "Content-Length: ".strlen($_post)."\r\n";  //数据长度
		$post_str .= "Connection:Close\r\n\r\n";
		$post_str .= $_post;  //传递post数据
		$header .= $post_str;
	}else{
		$header .= "Connection:Close\r\n\r\n";
	}
	fwrite($fp, $header);
	//echo fread($fp,1024);
	usleep(1000); // 这一句也是关键,如果没有这延时,可能在nginx服务器上就无法执行成功
	fclose($fp);
	return true;
}
_fsockopen('http://localhost/index.php'));
Copy after login

Related recommendations:

Detailed explanation of the difference between synchronous requests and asynchronous requests

Detailed explanation of examples of JavaScript implementation of Ajax asynchronous requests

Native JavaScript implements Ajax asynchronous request

The above is the detailed content of PHP implements sending asynchronous request method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!