본문 바로가기
Develop/PHP

PHP CURL 사용법

by bellsilver7 2020. 3. 5.
728x90

안녕하세요. 은은한 개발자입니다.

 

"curl is a comand line tool for transferring files with URL syntax" - Daniel Stenberg

 

curl 이란? URL 구문으로 파일을 전송하기 위한 커맨드라인 도구입니다.

 

 

[GET 방식]

function fn_curl_get($url) {

	// create curl resource
	$ch = curl_init();

	// set url
	curl_setopt($ch, CURLOPT_URL, $url);

	// return the transfer as a string
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	// $output contains the output string
	$output = curl_exec($ch);

	// close curl resource to free up system resources
	curl_close($ch);

	// return output
	return $output;

}

 

파라미터를 함께 넘기는 경우 저는 아래와 같이 파라미터를 인코딩해서 url 변수 뒤에 붙여 사용합니다.

$querystring = http_build_query($param, '', '&');
$url .= '?' . $querystring;

 

 

[POST 방식]

function fn_curl_post($url, $postvars) {

	// create curl resource
	$ch = curl_init();

	// set url
	curl_setopt($ch, CURLOPT_URL, $url);

	// set TRUE to do a regular HTTP POST
	curl_setopt($ch, CURLOPT_POST, true);

	// set the full data to post in a HTTP "POST" operation
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
    
	// return the transfer as a string
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	// $output contains the output string
	$output = curl_exec($ch);

	// close curl resource to free up system resources
	curl_close($ch);

	// return output
	return $output;

}

 

 

추가적인 옵션 설정 방법

 

- connection timeout : 초단위로 값을 입력하면 되고 무한대기를 원하면 0을 사용하면 됩니다.

// The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);

- HTTP Auth : basic auth

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "userid:userpwd");

 

728x90

댓글