[php] curl을 이용하여 post, get 방식 으로 데이터 전송하기 > PHP

본문 바로가기

PHP

[PHP] [php] curl을 이용하여 post, get 방식 으로 데이터 전송하기

회원사진
하나를하더라도최선을
2019-10-03 02:17 3,629 0

본문



GET과 POST에 대해 간단하게 논하겠습니다. 

GET은 눈에 보이는것, POST는 눈에 보이지 않는것이라 생각하면 됩니다. 즉 GET은 주소창에 http://itfresh.tistory.com/?a=1&b=2 와 같이 브라우져의 주소줄에 ? 다음에 변수값들을 넣는 방식이고, POST는 form전송과 같이 필드값으로 던져주는 형식입니다. 즉 일반 브라우져 화면에서는 볼 수 없습니다. 브라우져의 개발자모드를 통해서 확인 가능합니다.


php로 curl을 이용하여 각자의 방식으로 전송하는 샘플코드를 먼저 보여드리겠습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?
// GET 방식 함수
function get($url$params=array()) 
    $url = $url.'?'.http_build_query($params'''&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}
 
// get함수 호출
get('http://itfresh.tistory.com'array('param1'=>'value1''param2'=>'value2'));
 
 
// POST 방식 함수
function post($url$fields)
{
    $post_field_string = http_build_query($fields'''&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field_string);
    curl_setopt($ch, CURLOPT_POST, true);
    $response = curl_exec($ch);
    curl_close ($ch);
    return $response;
}
 
// post함수 호출
post('http://itfresh.tistory.com'array('field1'=>'value1''field2'=>'value2'));
?>
cs


curl에 보시면 setopt 에 CURLOPT_RETURNTRANSFER 라는 항목이 있습니다. 이것을 선언 하지 않으면 curl통신과 동시에 결과 코드가 변수에 담기지 않고 화면에 바로 뿌려지기 때문에 이렇게 변수에 결과값을 담을 필요가 있을 경우는 반드시 포함 해야 합니다.

댓글목록0

등록된 댓글이 없습니다.
게시판 전체검색