본문 바로가기
Program/PHP

curl 설치 및 사용법 - HTTP GET/POST, REST API 연계 - PHP CURL 로 Json data POST 하기

by 너부리공작소 2017. 7. 20.
반응형


<?php

class Log {

    public static function debug($str) {

        print "DEBUG: " . $str . "\n";

    }

    public static function info($str) {

        print "INFO: " . $str . "\n";

    }

}

function Curl($url, $post_data, &$http_status, &$header = null) {

    Log::debug("Curl $url JsonData=" . $post_data);

    $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);

    $response = curl_exec($ch);

    Log::debug('Curl exec=' . $url);

      

    $body = null;

    // error

    if (!$response) {

        $body = curl_error($ch);

        // HostNotFound, No route to Host, etc  Network related error

        $http_status = -1;

        Log::error("CURL Error: = " . $body);

    } 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://requestb.in/1h1tct81";

$json = "{\"name\" : \"UserName\", \"age\" : 12 }";

$ret = Curl($url, $json, $http_status);

var_dump($ret);

?>


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

반응형

댓글