PHP cURL 비동기 방식으로 호출 방법

컴퓨터,인터넷
(22.4k 포인트)
0 투표
PHP cURL 비동기 방식으로 요청 방법 있나요?

페이지 호출만 필요하고 결과는 필요 없거든요.

방법 아시는 분 알려주세요.

1 답변

0 투표

cURL을 이용하여 HTTP 프로토콜 데이터를 POST 방식으로 보내는 PHP 함수는 다음과 같습니다.

function https_post($uri, $postdata)
{
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
 
이 방식은 값이 전달될 때까지 블럭이 됩니다. 그렇기 때문에 결과값이 불필요한 경우에는 요청만 보내면 되는 방법에 문제가 됩니다. 그렇게 하려면 PHP 특성상 소켓을 열어서 직접 요청 처리 해야 합니다.(PHP 는 CURL 비동기 처리 라이브러리가 없습니다.)
function curl_request_async($url, $params, $type='POST')
{
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);
 
if ($parts['scheme'] == 'http')
{
$fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, 30);
}
else if ($parts['scheme'] == 'https')
{
$fp = fsockopen("ssl://" . $parts['host'], isset($parts['port'])?$parts['port']:443, $errno, $errstr, 30);
}
 
// Data goes in the path for a GET request
if('GET' == $type)
$parts['path'] .= '?'.$post_string;
 
$out = "$type ".$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";
// Data goes in the request body for a POST request
if ('POST' == $type && isset($post_string))
$out.= $post_string;
 
fwrite($fp, $out);
fclose($fp);
}
 

 

구로역 맛집 시흥동 맛집
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
add
...