php 从 URL 下载文件到服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3938534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:31:01  来源:igfitidea点击:

Download File to server from URL

phphttpstreamdownload

提问by xaav

Well, this one seems quite simple, and it is. All you have to do to download a file to your server is:

嗯,这个看起来很简单,确实如此。将文件下载到服务器所需要做的就是:

file_put_contents("Tmpfile.zip", file_get_contents("http://someurl/file.zip"));

Only there is one problem. What if you have a large file, like 100mb. Then, you will run out of memory, and not be able to download the file.

只有一个问题。如果你有一个大文件,比如 100mb。然后,您将耗尽内存,并且无法下载该文件。

What I want is a way to write the file to the disk as I am downloading it. That way, I can download bigger files, without running into memory problems.

我想要的是一种在下载文件时将文件写入磁盘的方法。这样,我可以下载更大的文件,而不会遇到内存问题。

回答by alex

Since PHP 5.1.0, file_put_contents()supports writing piece-by-piece by passing a stream-handle as the $dataparameter:

从 PHP 5.1.0 开始,file_put_contents()支持通过将流句柄作为$data参数传递来逐段编写:

file_put_contents("Tmpfile.zip", fopen("http://someurl/file.zip", 'r'));

From the manual:

从手册:

If data[that is the second argument] is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

如果data[即第二个参数] 是流资源,则该流的剩余缓冲区将被复制到指定的文件。这与使用 stream_copy_to_stream().

(Thanks Hakre.)

(感谢哈克雷。)

回答by xaav

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);
    }
}

回答by prodigitalson

Try using 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);

I'm not sure but I believe with the CURLOPT_FILEoption it writes as it pulls the data, ie. not buffered.

我不确定,但我相信CURLOPT_FILE它在提取数据时写入的选项,即。没有缓冲。

回答by Kamil Kie?czewski

prodigitalson's answerdidn't work for me. I got missing fopen in CURLOPT_FILEmore details.

prodigitalson 的回答对我不起作用。我得到了missing fopen in CURLOPT_FILE更多细节

This worked for me, including local urls:

这对我有用,包括本地网址:

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);
    }
}

回答by stra8edge

  1. Create a folder called "downloads" in destination server
  2. Save [this code] into .phpfile and run in destination server
  1. 在目标服务器中创建一个名为“downloads”的文件夹
  2. 将 [此代码] 保存到.php文件中并在目标服务器中运行

Downloader :

下载器:

<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> 

回答by Dimmy

set_time_limit(0); 
$file = file_get_contents('path of your file');
file_put_contents('file.ext', $file);

回答by Hoan Huynh

There are 3 ways:

有3种方式:

  1. file_get_contents and file_put_contents
  2. CURL
  3. fopen
  1. file_get_contents 和 file_put_contents
  2. 卷曲
  3. 打开

You can find examples from here.

您可以从这里找到示例。

回答by Pradeep Kumar Prabaharan

Use a simple method in php copy()

在php中使用一个简单的方法 copy()

copy($source_url, $local_path_with_file_name);

Note: if the destination file already exists, it will be overwritten

注意:如果目标文件已经存在,它将被覆盖

PHP copy() Function

PHP copy() 函数

Note: You need to set permission 777 for the destination folder. Use this method when you are downloading to your local machine.

注意:您需要为目标文件夹设置权限 777。下载到本地计算机时使用此方法。

Special Note: 777 is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.In general we give this permission to assets which are not much needed to be hidden from public on a web server. Example: images folder.

特别注意:777 是基于 Unix 的系统中的权限,具有所有者、组和所有人的完全读/写/执行权限。通常,我们会向不需要在 Web 服务器上公开隐藏的资产授予此权限。示例:图像文件夹。

回答by Hoàng V? Tgtt

I use this to download file

我用它来下载文件

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()";
}

回答by Eric Leroy

A PHP 4 & 5 Solution:

PHP 4 & 5 解决方案:

readfile()will not present any memory issues, even when sending large files, on its own. A URL can be used as a filename with this function if the fopen wrappers have been enabled.

readfile()本身不会出现任何内存问题,即使在发送大文件时也是如此。如果已启用 fopen 包装器,则可以将 URL 用作此函数的文件名。

http://php.net/manual/en/function.readfile.php

http://php.net/manual/en/function.readfile.php