PHP & Others

cURL을 이용한 원격지 파일의 다운로드

페이지 정보

본문

출처 : http://blog.naver.com/doskey?Redirect=Log&logNo=120107297825


<?php
$url = 'http://www.example.com/a-large-file.zip';
$path = '/path/to/a-large-file.zip';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);

curl_close($ch);

file_put_contents($path, $data);
?>
위의 방식은
file_put_contents()을 이용한 파일저장방식이다.
하지만, 큰 파일을 다운로드할 경우에는 로컬에 파일쓰기전에 메모리에 담기므로 메모리 초과 현상을 초래할 수 있다.

<?php
$url = 'http://www.example.com/a-large-file.zip';
$path = '/path/to/a-large-file.zip';

$fp = fopen($path, 'w');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);
?>
위의 방식으로 fopen() 파일 포인터를 생성하여 처리하는 것이 바람직하다.
fclose($fp)는 반드시 curl_close() 뒤에 삽입한다.
그리고 파일포인터 생성시 'w' 쓰기 권한만 가능하다고 되어있다. 읽기 속성까지 있는 경우 'rw' 는 에러발생.
(php.net 사용자코멘트 중에서)


## 파일의 일정 부분만 다운로드 할 경우
$ch = curl_init();
curl_setopt
($ch, CURLOPT_URL, '
http://www.example.com/a-large-file.zip');
curl_setopt
($ch, CURLOPT_RANGE, '0-500');
curl_setopt
($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt
($ch, CURLOPT_RETURNTRANSFER, 1);
$result
= curl_exec($ch);
curl_close
($ch);
echo $result
;



[참조]
http://kr2.php.net/manual/en/function.curl-setopt.php
http://www.phpriot.com/articles/download-with-curl-and-php
http://stackoverflow.com/questions/2032924/how-to-partially-download-a-remote-file-with-curl

보기좋은 떡이 먹기좋다고, 다른 블로그 사이트에서 사용하는 code highlighter가 부럽긴하다.

관련자료

등록된 댓글이 없습니다.
Today's proverb
참된 행복은 눈에 보이지 않는다. 참된 행복은 작지만 자기 일에 만족하고 자기 안에서 그것을 찾는 사람에게만 보이도록 가만 가만히 찾아온다.