본문 바로가기
PHP

[PHP] curl을 이용한 HTTP 통신

by teamnova 2021. 4. 3.

오늘 포스팅할 내용은 PHP의 curl 을 이용한 HTTP 통신입니다.

 

이번 내용은 이전에 작성한 URL Router을 이용하지만

그냥 curl 부분만 가져다가 자유롭게 사용해도 됩니다.

 

Router.php, select_from_idx.php, dbconnect.php 

 

등의 모든 코드는 스틱코드 포스팅에서 확인하실수 있습니다.

 

stickode.com/detail.html?no=1996

 

스틱코드

 

stickode.com

 

 

 

 

index.php

<?php
// Include router class
require   'Router.php';

Router::add('get','/curl_get',function(){
   require_once 'http/curl_get.php';
});


Router::add('get','/curl_post',function(){
    require_once 'http/curl_post.php';
});

Router::add('post','/curl_post',function(){
    print_r($_POST);
    echo "<br/><br/><br/>";
    echo file_get_contents('php://input') . "<br/><br/><br/>";
    $data = json_decode(file_get_contents('php://input'), true);
    print_r($data);
//    echo "hihi";
});

// idx(숫자, $var1) 값을 통해 유저 정보를 조회
Router::add('get','/user/([0-9-]+)',function($var1){
    require_once 'select_from_idx.php';
});



Router::run();

?>

 

간단하게 브라우저상에서 /curl_get , /curl_post 를 통해  response를 출력해 보겠습니다.

 

curl_get.php

<?php
$url = 'http://localhost/user/1';
$header_data = array(
//            'Authorization: Bearer '.$accesstoken,
    'Content-Type: application/json; charset=utf-8'
);
$ch = curl_init(); //curl 사용 전 초기화 필수(curl handle)
curl_setopt($ch, CURLOPT_URL, $url); //URL 지정하기
curl_setopt($ch, CURLOPT_HEADER, true);//헤더 정보를 보내도록 함(*필수)
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data); //header 지정하기
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); //이 옵션이 0으로 지정되면 curl_exec의 결과값을 브라우저에 바로 보여줌. 이 값을 1로 하면 결과값을 return하게 되어 변수에 저장 가능(테스트 시 기본값은 1)
$res = curl_exec ($ch);

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($res, 0, $header_size);
$body = substr($res, $header_size);
$body_decode = json_decode($body); // Array로 decode


echo $header."<br/><br/><br/><br/>";
echo $body."<br/><br/><br/><br/>";
echo print_r($body_decode);

 

 

요청에 대한 응답

 

 

curl_post.php

<?php
$body = array(
    "type"=>"타입",
    "subject"=>"ㅁㄴㅇㄹ.",
    "messages"=>[
        'key1'=>'value1',
        'key2'=>'value2'
    ]
);

$post_data = json_encode($body);
$url = 'http://localhost/curl_post';
$header_data = array(
    'Content-Type: application/json; charset=utf-8'
);

$ch = curl_init($url);
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => $header_data,
    CURLOPT_POSTFIELDS => $post_data
));

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

 

요청에 대한 응답

 

각각 curl을 통해 get, post 요청을 하고 response를 출력합니다.

 

get의 경우 header만

post의 경우 header ,body (raw json data) 를 세팅후 request 하고 response를 확인하는 코드입니다.

 

 

스틱코드를 이용하면 다음과같이 curl 요청을 간단하게 만들어서 사용할수 있습니다.