[PHP] Curl 함수 (GET,POST,PUT,DELETE)

// 함수 내용 20210324
function integralCurl(string $url, bool $isSsl = false, string $method = "GET", array $sendData = [], array $option = [], array $header = []) : array {
      $certificateLoc = "../inc/cacert.pem";
      $method = strtoupper($method);

      $defaultOptions = array(
            CURLOPT_RETURNTRANSFER => true
      ); 

      $ch = curl_init();
      curl_setopt_array($ch, $defaultOptions);

      if($method === "POST"){
            // $sendData 샘플
            // [
            //       "a" => 1,
            //       "b" => "22"
            // ]

            if(count($sendData) >= 1){
                  curl_setopt($ch, CURLOPT_POSTFIELDS, $sendData);
            }
      }elseif($method === "GET"){
            if(count($sendData) >= 1){
                  $paramsUrl = http_build_query($sendData);
                  $url .= "?" . $paramsUrl;
            }
      }elseif($method === "PUT"){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

            if(count($sendData) >= 1){
                  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($sendData));
            }
      }elseif($method === "DELETE"){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

            if(count($sendData) >= 1){
                  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($sendData));
            }
      }

      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, $method === "POST");

      if(count($option) >= 1){
            // $option 샘플
            // [
            //       CURLOPT_HEADER => false,
            //       CURLOPT_USERAGENT => "test"
            // ]

            curl_setopt_array($ch, $option);
      }

      if(count($header) >= 1){
            // $header 샘플
            // ['Authorization: Bearer '.$accessToken, 'Content-Type: application/x-www-form-urlencoded;charset=utf-8']

            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
      }

      if($isSsl === true && $certificateLoc != ""){
            curl_setopt($ch, CURLOPT_CAINFO, $certificateLoc);
      }

      $returnData  = curl_exec($ch);
      $returnState = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      if($returnData === false){
            $returnErr = "CURl ERROR: " . curl_error($ch);
      }else{
            $returnErr = "success";
      }

      curl_close($ch);

      return [
            "data" => $returnData,
            "code" => $returnState,
            "msg" => $returnErr
      ];
}

// 함수 사용 예제
$loginResponse = integralCurl("https://kauth.kakao.com/oauth/token", true, "GET", [
      "grant_type" => "authorization_code",
      "client_id" => $restAPIKey,
      "redirect_uri" => $callbacURI,
      "code" => $returnCode
])["data"];

Leave a Comment