출처 : http://www.seobangnim.com/zbxe/PHP/566476



cURL (Client URL Library Functions)

  • 제작자 Daniel Stenberg 의 설명을 그대로 변역하면
    curl is a comand line tool for transferring files with URL syntax
    커맨드라인에서 URL 문법을 사용하여 파일을 전송 프로그램
  • 내가 원하는 주소의 페이지에서 내가 임의의 값을 넣고 그 넣은 값으로 페이지에서 리턴되는 값을 받아오는 역할을 한다.
  • PHP에서 cURL을 사용하려는 사람들 대부분이 아마도 HTTPS 접속 때문일 것이다.
    소켓 또는 그 외 여러가지 접속방법이 있는데 굳이 cURL을 사용하는 건 속도면에서도 빠르고 HTTPS도 쉽게 접속할 수 있기 때문이다.
  • cURL 모듈을 서버에 설치해야 합니다.(리눅스 - curl.so, 윈도우 - php_curl.dll 확장모듈 필요)

 

cURL로 가능한 일

  • HTTPS certificates
  • HTTP POST
  • HTTP PUT
  • FTP upload
  • HTTP Form
  • cookie
  • authentication

 

cURL, Client URL Library Functions

  1. curl_init : 세션 초기화, 핸들값 리턴
  2. curl_setopt : 옵션 세팅
  3. curl_exec : curl을 실행
  4. curl_errno : 에러번호를 가져온다.
  5. curl_error : 에러 메시지를 가져온다.
  6. curl_getinfo : 상태 정보를 리턴한다.
  7. curl_close : curl 세션을 닫는다

 

[예제1 : POST방식으로 데이터 전송(simple)]

<?
$post_data = array(
      "name"   => "홍길동",
      "birthday"   => "1980-08-20"
      );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, http://www.example.com);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_exec($ch);
?>

 

[예제2: POST방식으로 데이터 전송(function)]

<?
function fetch_page($url,$param,$cookies,$referer_url){
    if(strlen(trim($referer_url)) == 0) $referer_url= $url; 
    $curlsession = curl_init ();
    curl_setopt ($curlsession, CURLOPT_URL, \"$url\");
    curl_setopt ($curlsession, CURLOPT_POST, 1);
    curl_setopt ($curlsession, CURLOPT_POSTFIELDS, \"$param\");
    curl_setopt ($curlsession, CURLOPT_POSTFIELDSIZE, 0);
    curl_setopt ($curlsession, CURLOPT_TIMEOUT, 60);
    if($cookies && $cookies!=\"\"){
        curl_setopt ($curlsession, CURLOPT_COOKIE, \"$cookies\");
    }
    curl_setopt ($curlsession, CURLOPT_HEADER, 1); //헤더값을 가져오기위해 사용합니다. 쿠키를 가져오려고요.
    curl_setopt ($curlsession, CURLOPT_USERAGENT, \"Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)\");
    curl_setopt ($curlsession, CURLOPT_REFERER, \"$referer_url\"); 
    ob_start();
    $res = curl_exec ($curlsession);
    $buffer = ob_get_contents();
    ob_end_clean();
    if (!$buffer) {
        $returnVal = \"Curl Fetch Error : \".curl_error($curlsession);
    }else{
        $returnVal = $buffer;
    } 
    curl_close($curlsession); 
    return $returnVal;

?>



[예제3 : 파일 전송]

<?
$post_data['data[0]'] = "@image/img_01.jpg";
$post_data['data[0]'] = "@image/img_02.jpg";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, http://www.example.com/upload.php);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$postResult = curl_exec($ch);
?>

[예제4 : https 접속]

<?
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL,"https://www.test.com"); //접속할 URL 주소
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 인증서 체크같은데 true 시 안되는 경우가 많다.
// default 값이 true 이기때문에 이부분을 조심 (https 접속시에 필요)
curl_setopt ($ch, CURLOPT_SSLVERSION,3); // SSL 버젼 (https 접속시에 필요)
curl_setopt ($ch, CURLOPT_HEADER, 0); // 헤더 출력 여부
curl_setopt ($ch, CURLOPT_POST, 1); // Post Get 접속 여부
curl_setopt ($ch, CURLOPT_POSTFIELDS, "var1=str1&var2=str2"); // Post 값  Get 방식처럼적는다.
curl_setopt ($ch, CURLOPT_TIMEOUT, 30); // TimeOut 값
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // 결과값을 받을것인지
$result = curl_exec ($ch);
curl_close ($ch);
echo $result;
?>

 

[예제5 : curl을 이용한 Gmail 로그인]

$src = "https://".$gmailId.":".$gmailPw."@mail.google.com/mail/feed/atom";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'My Agent Name');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$res = curl_exec($ch);
curl_close($ch);
/** 결과는 Atom xml 형식이다. DOM 또는 xml 파싱 function을 이용해서 파싱하면 됩니다. **/
echo $res;
?>

 

[예제6 : cURL을 이용한 웹페이지 가져오기]

<?php
function get_content($url) {
    $agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)';
    $curlsession = curl_init ();
    curl_setopt ($curlsession, CURLOPT_URL,             $url);
    curl_setopt ($curlsession, CURLOPT_HEADER,          0);
    curl_setopt ($curlsession, CURLOPT_RETURNTRANSFER,  1);
    curl_setopt ($curlsession, CURLOPT_POST,            0);
    curl_setopt ($curlsession, CURLOPT_USERAGENT,       $agent);
    curl_setopt ($curlsession, CURLOPT_REFERER,         "");
    curl_setopt ($curlsession, CURLOPT_TIMEOUT,         3);
    $buffer = curl_exec ($curlsession);
    $cinfo = curl_getinfo($curlsession);
    curl_close($curlsession);
    if ($cinfo['http_code'] != 200)
    {
        return "";
    }
    return $buffer;
}
?>