본문 바로가기

php

curl 대체 코드

반응형

제목 그대로 php에서 curl 을 사용하고 싶은데 사용하지 못하는 경우 사용한 코드이다.

해당 문제는 APM 를 배포하는 부분에서 발생했다.

APM 을 배포하여 아파치와 PHP가 새로운 환경에 설치되는데 해당 PC에서 오류가 났었다.

분명 내 PC에서 테스트시 문제가 없었지만 새로운 환경으로 배포하면 오류가 생기는 상황이라 당황스러웠다.

코드도 완벽히 같은 상황에서 확인해보니 curl 사용하여 외부 api 를 호출하는 부분에서 오류가 생겼다.

내가 테스트했던 pc인 경우 curl 을 설치했던 이력이 있어서 문제가 없었지만 새롭게 설치되는 환경에서는 해당 설치가 이뤄지지 않았기에 오류가 생겼던 것이다.

매 환경마다 curl을 설치할 수는 없기에 curl을 사용하지 않기로 했다.

 

다음은 대체 코드이다

GET 호출

// CURL 사용
public function _send_get_curl($url, $data,$type=""){
    try{
        $get_url = $url . "?" . http_build_query($data, '', '&');

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

        if($type!=""){
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: '.$type));
        }
        
        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
        
    } catch(Exception $e){
        return;
    }
}

// 대체 코드
public function send_get_curl($url, $data, $type = "") {

        try {
            $get_url = $url . "?" . http_build_query($data, '', '&');

            // HTTP 헤더 설정
            $options = array(
                'http' => array(
                    'method' => 'GET',
                    'timeout' => 10,  // connection timeout 10초
                    'header' => ""
                )
            );

            // Content-Type 설정 (만약 지정된 타입이 있으면)
            if ($type != "") {
                $options['http']['header'] .= "Accept: application/json\r\n";
                $options['http']['header'] .= "Content-Type: " . $type . "\r\n";
            }

            // SSL 인증서 검사를 건너뛰도록 설정
            $options['ssl'] = array(
                'verify_peer' => false,
                'verify_peer_name' => false,
            );

            // 스트림 컨텍스트 생성
            $context = stream_context_create($options);

            $response = file_get_contents($get_url, false, $context);

            return $response;

        } catch (Exception $e) {
            return;
        }
    }

 

 

POST 호출

// CURL 사용
public function _send_post_curl($url, $data){

    try{
            $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }catch(Exception $e){
            return ;
    }
}

// 대체 코드
public function send_post_curl($url, $data) {

    try {
        // POST 요청을 위한 HTTP 옵션 설정
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header'  => "Content-Type: application/json\r\n",  // 헤더 설정
                'content' => json_encode($data),  // POST 데이터 설정 (JSON으로 인코딩)
                'timeout' => 10,  // connection timeout 설정
            ),
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
            )
        );

        // 스트림 컨텍스트 생성
        $context = stream_context_create($options);
        
        $response = file_get_contents($url, false, $context);

        return $response;

    } catch (Exception $e) {
        return;
    }
}
반응형

'php' 카테고리의 다른 글

php header text파일 다운로드  (2) 2024.09.30
php empty  (0) 2024.04.26