cURL(Client URL Library)
URL을 사용하여 서버와 연결, 다양한 데이터를 전송하는 프로그램으로
저는 Rest API 통신시 자주 사용하고 있습니다.
https://www.php.net/manual/en/intro.curl.php
cURL GET방식 예제
$api_server = 'https://도메인'; // get으로 보낼 array $params = array('key1'=>'val1', 'key2'=>'val2'); $query = http_build_query($params); $opts = array( CURLOPT_URL => $api_server . '?' . $query, CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, ); // 응답요청 $curl_session = curl_init(); curl_setopt_array($curl_session, $opts); $curl_response = curl_exec($curl_session); $resMessage = (curl_error($curl_session))? null : $curl_response; //print_r($curl_response); $body = null; if (curl_error($curl_session)) { // 실패 $err = curl_errno($curl_session); $errmsg = curl_error($curl_session); } else { // 성공 $header_size = curl_getinfo($curl_session, CURLINFO_HEADER_SIZE); $header = substr($curl_response, 0, $header_size); // 헤더 $body = substr($curl_response, $header_size); // 응답전문 $json_de = json_decode($body, true); //print_r($json_de); } curl_close($curl_session);
$api_server = "https://도메인"; // 요청전문 작성 $post_body = array(); $post_body['param1'] = "값1"; $post_body['param2'] = "값2"; $post_json = json_encode($post_body, JSON_UNESCAPED_UNICODE); $opts = array( CURLOPT_URL => $api_server, CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POST => true, CURLOPT_POSTFIELDS => $post_json, //CURLOPT_POSTFIELDSIZE => 1000, CURLOPT_TIMEOUT => 10, ); // 응답요청 $curl_session = curl_init(); curl_setopt_array($curl_session, $opts); $curl_response = curl_exec($curl_session); $resMessage = (curl_error($curl_session))? null : $curl_response; //print_r($curl_response); $body = null; if (curl_error($curl_session)) { // 실패 $err = curl_errno($curl_session); $errmsg = curl_error($curl_session); } else { // 성공 $header_size = curl_getinfo($curl_session, CURLINFO_HEADER_SIZE); $header = substr($curl_response, 0, $header_size); // 헤더 $body = substr($curl_response, $header_size); // 응답전문 $json_de = json_decode($body, true); //print_r($json_de); } curl_close($curl_session);curl_init : 새로운 cURL 리소스생성(초기화)