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을 php 모듈과 연결해줘야 한다.
sudo apt-get install php5-curl
혹은
sudo apt-get install php7.0-curl
snoopy도 한번 볼 것.
<?php $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); ?>
<?php 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; } ?>
<?php $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); ?>
<?php $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; ?>
<?php $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; ?>
<?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; } ?>
$url = 'someurliwanttoscrape'; $cookie_string = 'somecookies'; $useragent = 'someuseragent'; $timeout = 60; $rawhtml = curl_init(); curl_setopt ($rawhtml, CURLOPT_URL,$url); curl_setopt ($rawhtml, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($rawhtml, CURLOPT_REFERER, ''); curl_setopt ($rawhtml, CURLOPT_COOKIE, $cookie_string); curl_setopt ($rawhtml, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt ($rawhtml, CURLOPT_USERAGENT, $userAgent); $output = curl_exec($rawhtml); curl_close($rawhtml);
function curl($url) { // http://www.partner114.com/bbs/board.php?bo_table=B07&wr_id=126 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $g = curl_exec($ch); curl_close($ch); return $g; }
cURL 세션을 닫고, 리소스를 비워준다. 또한 cURL 핸들은 삭제된다.
만일 연산 후 어떠한 에러도 발행하지 않았다면 0(zero)을 리턴한다.
There exists a bunch of different error codes and their corresponding error messages that may appear during bad conditions. At the time of this writing, the exit codes are:
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); ?>
이 함수는 cURL 세션을 초기화하고 세션의 옵션들을 셋팅한 후에 불려져야만 한다. 본 함수의 목적은 단순히 미리 정의된 cURL 세션을 실행하기 위한 것이기 때문이다.
TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set). FOLLOWLOCATION 옵션 설정. 위치 헤더가 존재하면 따라간다. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, tru
TRUE to include the header in the output. 헤더 정보를 받기 원한다면 이 옵션을 추가한다.
VALUE : 1 OR true
curl_setopt($ch, CURLOPT_HEADER, false);
TRUE to exclude the body from the output. 본문의 정보를 받기 원하지 않는다면 이 옵션을 추가한다.
TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms. 전송 메소드를 설정한다.
VALUE : 1-POST, 0-GET curl_setopt($ch, CURLOPT_POST,1);
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. REQUEST 에 대한 결과값을 받을 건지 체크
(WRITERUNCTION 콜백을 사용하는 대신, curl_exec 함수을 위한 반환 값으로 원격지 내용을 받는다.) #Resource ID 형태로 넘어옴 :: 내장 함수 curl_errno 로 체크 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2). 인증서 체크같은데 true 시 안되는 경우가 많다. default 값이 true 이기때문에 이 부분을 조심 (https 접속시에 필요) curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
An alternative port number to connect to.
CURLOPT_SSLVERSION The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases this must be set manually. SSL 버젼 (https 접속시에 필요) curl_setopt ($ch, CURLOPT_SSLVERSION,3);
The maximum number of seconds to allow cURL functions to execute. REQUEST 에 대한 결과값을 받는 시간타임 설정한다. curl_setopt($ch, CURLOPT_TIMEOUT,100);
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. POST 메소드라면 파라미터 값들을 이 옵션에 정의하면 된다.
curl_setopt($cu, CURLOPT_POSTFIELDS,$vars);
보낼 데이타 형식은 GET 방식으로 설정
ex) $vars = "arg=$arg1&arg2=$arg2&arg3=$arg3";
The contents of the "Referer: " header to be used in a HTTP request. 리퍼러 정보를 설정
The URL to fetch. This can also be set when initializing a session with curl_init(). 접속할 url정보를 설정 curl_init()에서 url를 설정하면 별도 설정이 필요없다.
curl_setopt($ch, CURLOPT_URL, 'http://www.exsample.com');
The contents of the "User-Agent: " header to be used in a HTTP request.
에이전트 정보를 설정
curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
누구나 수정할 수 있다. 위키 사용법 참고하라. |
---|