티스토리 뷰

웹개발/Php

PHP CURL 정리

yaku 2010. 9. 1. 16:08
http://blog.naver.com/PostView.nhn?blogId=bak35u&logNo=10090777896


curl_setopt 의 옵션

CURLOPT_HEADER : 헤더 정보를 받기 원한다면 이 옵션을 추가한다. VALUE : 1 OR true

CURLOPT_NOBODY :  본문의 정보를 받기 원하지 않는다면 이 옵션을 추가한다.
CURLOPT_TIMEOUT : curl 타임아웃을 설정한다.
CURLOPT_URL : 접속할 url정보를 설정
CURLOPT_REFERER : 리퍼러 정보를 설정
CURLOPT_USERAGENT : 에이전트 정보를 설정
CURLOPT_POST : 전송 메소드를 post로 정의한다.
CURLOPT_POSTFIELDS: POST 메소드라면 파라미터 값들을 이 옵션에 정의하면된다.
CURLOPT_PUT  TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.

CURLOPT_RETURNTRANSFER  curl_exec() 결과를 직접 밖으로 호출합니다.
curl_setopt(CURLOPT_POSTFIELDS, array('field1' => 'value'));
curl_setopt(CURLOPT_POSTFIELDS, array('field1=value&field2=value2'));

XML  샌드
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));

CURLOPT_CRLF TRUE로 전송에 CRLF를 뉴라인 유닉스 뉴라인 변환합니다.
CURLOPT_FAILONERROR 기본 TRUE 에러를 반환 400 , 300 번등
CURLOPT_FILETIME  파일 시간 검사
CURLOPT_FORBID_REUSE
OPT_FTP_USE_EPRT
CURLINFO_HEADER_OUT
CURLOPT_NETRC


$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$data = curl_exec($ch);

var_dump($data);

curl_setopt($this->curl, CURLOPT_WRITEFUNCTION, array($this, "curl_handler_recv"));


curl_getinfo($ch);

반환 값

"url"
"content_type"
"http_code"
"header_size"
"request_size"
"filetime"
"ssl_verify_result"
"redirect_count"
"total_time"
"namelookup_time"
"connect_time"
"pretransfer_time"
"size_upload"
"size_download"
"speed_download"
"speed_upload"
"download_content_length"
"upload_content_length"
"starttransfer_time"
"redirect_time"


 

예제들 소스

// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');

// Execute
curl_exec($ch);

// Check if any error occured
if(!curl_errno($ch))
{
 $info = curl_getinfo($ch);

 echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}

// Close handle
curl_close($ch);

결과..
Took 0.554 seconds to send a request to http://www.yahoo.com/


PUT

function doPut($url, $fields)
{
   $fields = (is_array($fields)) ? http_build_query($fields) : $fields;

   if($ch = curl_init($url))
   {
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
      curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
      curl_exec($ch);

      $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      curl_close($ch);

      return (int) $status;
   }
   else
   {
      return false;
   }
}

function redirect_exec($ch, $curlopt_header = false)
{
 curl_setopt($ch, CURLOPT_HEADER, true);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $data = curl_exec($ch);
 $info =    curl_getinfo($ch);
 $http_code = $info['http_code'];
 if ($http_code == 301 || $http_code == 302 || $http_code == 303) {
  list($header) = explode("\r\n\r\n", $data, 2);
  $matches = array();
  preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
  $url = trim(array_pop($matches));
  $url_parsed = parse_url($url);
  if (isset($url_parsed['host'])) {
   curl_setopt($ch, CURLOPT_URL, $url);
   return redirect_exec($ch);
  }
 }

 elseif($http_code == 200){
  $matches = array();
  preg_match('/(/', strtolower($data), $matches);
  $url = trim(array_pop($matches));
  $url_parsed = parse_url($url);
  if (isset($url_parsed['host'])) {
   curl_setopt($ch, CURLOPT_URL, $url);
   return redirect_exec($ch);
  }
 }

 return     $info['url'];
}

function curl_data_post($post, $page, $n, $session, $referer)
{
 if(!is_array($post))
 {
  return false;
 }

 $DATA_POST = curl_init();
 curl_setopt($DATA_POST, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($DATA_POST, CURLOPT_URL, $page);
 curl_setopt($DATA_POST, CURLOPT_POST, true);
 if($n)
 {
  curl_setopt($DATA_POST, CURLOPT_FOLLOWLOCATION, true);
 }
 if($session)
 {
  curl_setopt($DATA_POST, CURLOPT_COOKIEFILE, 'cookiefile.txt');
  curl_setopt($DATA_POST, CURLOPT_COOKIEJAR, 'cookiefile.txt');
 }

 if($referer)
 {
  curl_setopt($DATA_POST, CURLOPT_REFERER, $referer);
 }

 curl_setopt($DATA_POST, CURLOPT_POSTFIELDS, $post);
 $data = curl_exec($DATA_POST);
 if($data == false)
 {
  echo'Warning : ' . curl_error($DATA_POST);
  curl_close($DATA_POST);
  return false;
 }
 else
 {
  curl_close($DATA_POST);
  return $data;
 }
}

$fh = fopen('/tmp/foo', 'w');
$ch = curl_init('http://example.com/foo');
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);

# at this point your file is not complete and corrupted

fclose($fh);

# now you can use your file;

read_file('/tmp/foo');


셰션 쿠기 전송

session_start();
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
session_write_close();

$curl_handle = curl_init('enter_external_url_here');
curl_setopt( $curl_handle, CURLOPT_COOKIE, $strCookie );
curl_exec($curl_handle);
curl_close($curl_handle);


// disguises the curl using fake headers and a fake user agent.
function disguise_curl($url)
{
  $curl = curl_init();

  // Setup headers - I used the same headers from Firefox version 2.0.0.6
  // below was split up because php.net said the line was too long. :/
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: 300";
  $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "Pragma: "; // browsers keep this blank.

  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);

  $html = curl_exec($curl); // execute the curl command
  curl_close($curl); // close the connection

  return $html; // and finally, return $html
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/start.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();      // Prevent output
curl_exec ($ch);
ob_end_clean();  // End preventing output
curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "field1=".$f1."&field2=".$f2."&SomeFlag=True");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/Login.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec ($ch);
curl_close ($ch);

// INIT CURL
$ch = curl_init();

// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Login.php');

// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);

// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'fieldname1=fieldvalue1&fieldname2=fieldvalue2');

// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

# Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
# not to print out the results of its query.
# Instead, it will return the results as a string return value
# from curl_exec() instead of the usual true/false.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

// EXECUTE 1st REQUEST (FORM LOGIN)
$store = curl_exec ($ch);

// SET FILE TO DOWNLOAD
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Downloads/AnnualReport.pdf');

// EXECUTE 2nd REQUEST (FILE DOWNLOAD)
$content = curl_exec ($ch);

'웹개발 > Php' 카테고리의 다른 글

XDEBUG PROFILE  (0) 2010.12.15
PHP 매직 메소드  (0) 2010.11.25
Php Session 정보  (0) 2010.11.24
추상 팩토리 패턴 그리고 의존성 주입에 대한 내 생각  (0) 2010.09.03
데코레이터 패턴 정리  (0) 2010.07.05
댓글
D-DAY
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/11   »
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
글 보관함