URL에서 서버로 파일 다운로드
글쎄요, 이것은 매우 단순 해 보입니다. 서버로 파일을 다운로드하기 위해해야 할 일은 다음과 같습니다.
file_put_contents("Tmpfile.zip", file_get_contents("http://someurl/file.zip"));
하나의 문제 만 있습니다. 100mb와 같은 큰 파일이 있으면 어떻게해야합니까? 그런 다음 메모리가 부족하여 파일을 다운로드 할 수 없습니다.
내가 원하는 것은 파일을 다운로드 할 때 디스크에 파일을 쓰는 방법입니다. 그렇게하면 메모리 문제가 발생하지 않고 더 큰 파일을 다운로드 할 수 있습니다.
PHP 5.1.0부터는 file_put_contents()
스트림 핸들을 $data
매개 변수 로 전달하여 조각 단위로 쓰기를 지원합니다 .
file_put_contents("Tmpfile.zip", fopen("http://someurl/file.zip", 'r'));
매뉴얼에서 :
경우 데이터 [즉, 두 번째 인자 인] 스트림 자원, 즉 스트림의 나머지 버퍼 지정된 파일에 복사한다. 이것은을 사용하는 것과 비슷
stream_copy_to_stream()
합니다.
private function downloadFile($url, $path)
{
$newfname = $path;
$file = fopen ($url, 'rb');
if ($file) {
$newf = fopen ($newfname, 'wb');
if ($newf) {
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
cURL을 사용해보십시오
set_time_limit(0); // unlimited max execution time
$options = array(
CURLOPT_FILE => '/path/to/download/the/file/to.zip',
CURLOPT_TIMEOUT => 28800, // set this to 8 hours so we dont timeout on big files
CURLOPT_URL => 'http://remoteserver.com/path/to/big/file.zip',
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
확실하지 않지만 CURLOPT_FILE
데이터를 가져올 때 쓰는 옵션, 즉 믿습니다 . 버퍼링되지 않았습니다.
examle 코드 wchih없는 일이 (prodigitalson 인용)으로 한 것입니다 (이유는 : CURLOPT_FILE에서 fopen의 누락 - http://www.webdeveloper.com/forum/showthread.php?268299-RESOLVED-PHP-script-for-a- cronjob-download-file-unpzck-run-another-php-script )로 이동하십시오. 점수가 너무 적으므로 주석을 추가 할 수 없으므로 아래에 작업 예제를 제공합니다 ( "local url"에서도 작동 함).
function downloadUrlToFile($url, $outFileName)
{
if(is_file($url)) {
copy($url, $outFileName);
} else {
$options = array(
CURLOPT_FILE => fopen($outFileName, 'w'),
CURLOPT_TIMEOUT => 28800, // set this to 8 hours so we dont timeout on big files
CURLOPT_URL => $url
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
}
}
- 대상 서버에 "downloads"라는 폴더를 만듭니다.
- [이 코드]를
.php
파일 로 저장하고 대상 서버에서 실행
다운로더 :
<html>
<form method="post">
<input name="url" size="50" />
<input name="submit" type="submit" />
</form>
<?php
// maximum execution time in seconds
set_time_limit (24 * 60 * 60);
if (!isset($_POST['submit'])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = 'downloads/';
$url = $_POST['url'];
$newfname = $destination_folder . basename($url);
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
?>
</html>
set_time_limit(0);
$file = file_get_contents('path of your file');
file_put_contents('file.ext', $file);
세 가지 방법이 있습니다.
- file_get_contents 및 file_put_contents
- 곱슬 곱슬하다
- 열다
PHP에서 간단한 방법을 사용하십시오 copy()
copy($source_url, $local_path_with_file_name);
참고 : 대상 파일이 이미 존재하면 덮어 씁니다.
참고 : 대상 폴더에 대한 권한 777을 설정해야합니다. 로컬 컴퓨터로 다운로드 할 때이 방법을 사용하십시오.
특별 참고 사항 : 777은 Unix 기반 시스템에서 소유자, 그룹 및 모든 사람에게 완전한 읽기 / 쓰기 / 실행 권한이있는 권한입니다. 일반적으로 우리는 웹 서버에서 공개적으로 숨길 필요가없는 자산에이 권한을 부여합니다. 예 : 이미지 폴더
이것을 사용하여 파일을 다운로드합니다
function cURLcheckBasicFunctions()
{
if( !function_exists("curl_init") &&
!function_exists("curl_setopt") &&
!function_exists("curl_exec") &&
!function_exists("curl_close") ) return false;
else return true;
}
/*
* Returns string status information.
* Can be changed to int or bool return types.
*/
function cURLdownload($url, $file)
{
if( !cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions";
$ch = curl_init();
if($ch)
{
$fp = fopen($file, "w");
if($fp)
{
if( !curl_setopt($ch, CURLOPT_URL, $url) )
{
fclose($fp); // to match fopen()
curl_close($ch); // to match curl_init()
return "FAIL: curl_setopt(CURLOPT_URL)";
}
if ((!ini_get('open_basedir') && !ini_get('safe_mode')) || $redirects < 1) {
curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_REFERER, 'http://domain.com/');
if( !curl_setopt($ch, CURLOPT_HEADER, $curlopt_header)) return "FAIL: curl_setopt(CURLOPT_HEADER)";
if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirects > 0)) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
if( !curl_setopt($ch, CURLOPT_MAXREDIRS, $redirects) ) return "FAIL: curl_setopt(CURLOPT_MAXREDIRS)";
return curl_exec($ch);
} else {
curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_REFERER, 'http://domain.com/');
if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false)) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
if( !curl_setopt($ch, CURLOPT_HEADER, true)) return "FAIL: curl_setopt(CURLOPT_HEADER)";
if( !curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)) return "FAIL: curl_setopt(CURLOPT_RETURNTRANSFER)";
if( !curl_setopt($ch, CURLOPT_FORBID_REUSE, false)) return "FAIL: curl_setopt(CURLOPT_FORBID_REUSE)";
curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
}
// if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true) ) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
// if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
// if( !curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)";
if( !curl_exec($ch) ) return "FAIL: curl_exec()";
curl_close($ch);
fclose($fp);
return "SUCCESS: $file [$url]";
}
else return "FAIL: fopen()";
}
else return "FAIL: curl_init()";
}
PHP 4 & 5 솔루션 :
readfile () 은 자체적으로 큰 파일을 보낼 때에도 메모리 문제를 나타내지 않습니다. fopen 래퍼가 활성화 된 경우이 기능을 사용하여 URL을 파일 이름으로 사용할 수 있습니다.
http://php.net/manual/en/function.readfile.php
참고 URL : https://stackoverflow.com/questions/3938534/download-file-to-server-from-url
'Programing' 카테고리의 다른 글
AngularJS에서 앵커 해시 링크를 처리하는 방법 (0) | 2020.03.08 |
---|---|
Linq 쿼리 결과를 사전으로 변환 (0) | 2020.03.08 |
==와 strcmp를 사용한 문자열 비교 (0) | 2020.03.08 |
Git의 현재 지점 만 표시 (0) | 2020.03.08 |
보다 쉬운 Windows 서비스 디버깅 방법 (0) | 2020.03.08 |