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
자기 자리의 중요성을 아는 사람은 절대로 외로움이나 쓸쓸함 따위를 느끼지 않는다. 나를 기억하고 있는 단 한 사람이라도 있다면, 나를 필요로 하는 곳이 단 한 군데만이라도 있다면 그 사람은 매우 행복한 사람이 아닐까. 지금, 이 자리의, 자신으로부터 작지만, 결코 작지 않은 새로운 역사가 시작되는 것이다. (안도현)