본문으로 바로가기

PHP CURL 로 Json 호출

category [ Web 관련 ]/php 2019. 6. 21. 17:47
//Curl 연결 함수
function Curl($url, $post_data, &$header = null) {

    $ch=curl_init();
    // user credencial
    curl_setopt($ch, CURLOPT_USERPWD, "username:passwd");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    // post_data
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    if (!is_null($header)) {
        curl_setopt($ch, CURLOPT_HEADER, true);
    }
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_VERBOSE, true);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);


    $body = null;
    // error
    if (!$response) {
        $body = curl_error($ch);
        // HostNotFound, No route to Host, etc  Network related error
        $http_status = -1;

    } else {
        //parsing http status code
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (!is_null($header)) {
            $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header = substr($response, 0, $header_size);
            $body = substr($response, $header_size);
        } else {
            $body = $response;
        }
    }
    curl_close($ch);
    return $body;
}

 

$url = "http://주소";
$json = '{"name" : "UserName", "age" : 12 }';
$ret = Curl($url, $json);

echo $ret;

출처 : https://www.lesstif.com/pages/viewpage.action?pageId=17105778

 

 

'[ Web 관련 ] > php' 카테고리의 다른 글

PHP 에서 Undefined index: 오류발생시  (0) 2019.07.11
php 에서 pdf출력 (tcpdf)  (0) 2019.06.24
CentOS + php + Oracle 연결 참조  (0) 2019.06.21
php 로그파일 만들기  (0) 2019.06.20
php 휴일을 제외한 업무 일수 계산  (0) 2019.06.18