PHP CURL 사용법 (GET, POST)

cURL이란? 


다양한 프로토콜로 데이터 전송이 가능한 Command Line Tool이다. 




cURL 사용법


1) GET 방식


1
2
3
4
5
6
7
8
9
10
11
12
$data = array(
'test' => 'test'
);

$url = "https://www.naver.com" . "?" , http_build_query($data, '', );

$ch = curl_init();                                 //curl 초기화
curl_setopt($ch, CURLOPT_URL, $url);               //URL 지정하기
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    //요청 결과를 문자열로 반환 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);      //connection timeout 10초 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   //원격 서버의 인증서가 유효한지 검사 안함
 
$response = curl_exec($ch);
curl_close($ch);
 
return $response;
cs




2) POST 방식 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$data = array(
    'test' => 'test'
);
 
$url = "https://www.naver.com";
 
$ch = curl_init();                                 //curl 초기화
curl_setopt($ch, CURLOPT_URL, $url);               //URL 지정하기
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    //요청 결과를 문자열로 반환 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);      //connection timeout 10초 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   //원격 서버의 인증서가 유효한지 검사 안함
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);       //POST data
curl_setopt($ch, CURLOPT_POST, true);              //true시 post 전송 
 
$response = curl_exec($ch);
curl_close($ch);
 
return $response;
 
cs



3) 결과 값 및 오류 확인

 

1
2
3
4
5
6
$response = curl_exec ($ch);
 
var_dump($response);        //결과 값 출력
print_r(curl_getinfo($ch)); //모든 정보 출력
echo curl_errno($ch);       //에러 정보 출력
echo curl_error($ch);       //에러 정보 출력
cs


Tags

Read Next