php没有直接支持异步请求,可以通过 fsockopen 等方式曲线实现
以下方案适合向大量微信公众号用户推送消息的场景下使用,关键在于 path 与 query的拼接
function funCurlRequestAsync($url, $param = [])
{
$parse_url = parse_url($url);
$scheme = $parse_url['scheme'];
if (empty($parse_url['query'])) {
$path = $parse_url['path'];
} else {
$path = $parse_url['path'] . '?' . $parse_url['query'];
}
if ($scheme == 'https') {
$host = 'ssl://' . $parse_url['host'];
} else {
$host = $parse_url['host'];
}
if (isset($parse_url['port'])) {
$port = $parse_url['port'];
} else {
$port = $scheme == 'https' ? 443 : 80;
}
$postData = json_encode($param);
$header = "POST $path HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Content-Type: application/json\r\n";
$header .= "Content-Length: " . strlen($postData) . "\r\n";
$header .= "Connection: Close\r\n\r\n";
$header .= $postData;
$fp = fsockopen($host, $port, $error_code, $error_msg, 1);
if (!$fp) {
return ['error_code' => $error_code, 'error_msg' => $error_msg];
} else {
stream_set_blocking($fp, 0);
stream_set_timeout($fp, 10);
fwrite($fp, $header);
usleep(2000); // 延时,防止在nginx服务器上无法执行成功
fclose($fp);
return ['error_code' => 0];
}
}
原创文章,作者:witersen,如若转载,请注明出处:https://www.witersen.com