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
우리는 유리할 때는 형제가 되고, 불리할 때는 남이 되며, 이로울 때는 친구가 되고, 해로울 때는 원수가 되는 그러한 인간관계를 증오한다. (북녘 하늘의 명언)