【问题标题】:Save external files by php通过php保存外部文件
【发布时间】:2011-03-29 00:21:22
【问题描述】:

我有一个带有 url 的数组,例如:

[1] = http://site.com/1.pdf
[2] = http://site.com/234234234.png
[3] = http://site.com/archive.zip
[4] = http://site.com/1f41f.anyformat
[5] = http://site.com/file.txt

如何通过 PHP 将它们保存到我的 ftp 上的某个文件夹中?

文件的名称不应更改。

【问题讨论】:

  • 为了让它们使用可能的 curl,将它们存储在 FTP 上,使用 FTP 扩展,这就是它的用途:) 文档中的示例非常丰富。

标签: php html arrays file


【解决方案1】:

这是一个简单的例子:

$urls = array('url1', 'url2');
foreach($urls as $url) {
   $data = file_get_contents($url);
   file_put_contents('/path/to/folder/'.basename($url), $data);
}

【讨论】:

    【解决方案2】:

    也许这会帮助你解决问题

    function remote_merge($sourceurl,$targetftp){
        $ch = curl_init ($sourceurl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
        $rawdata=curl_exec($ch);
        curl_close ($ch);
        $tempfile = "/path/to/temp/".basename(parse_url($sourceurl, PHP_URL_PATH));
        if(file_exists($tempfile)){
            unlink($tempfile);
        }
        $fp = fopen($tempfile,'x');
        fwrite($fp, $rawdata);
        fclose($fp);
    
        $ch = curl_init();  
        $fp = fopen($tempfile, "rb");
    
        curl_setopt($ch, CURLOPT_URL, $targetftp);
        curl_setopt($ch, CURLOPT_UPLOAD, 1);
        curl_setopt($ch, CURLOPT_INFILE, $fp);
        curl_setopt($ch, CURLOPT_INFILESIZE, filesize($tempfile));
        $error = curl_exec($ch);
        // check $error here to see if it did fine or not!
        curl_close($ch); 
    }
    

    使用它来试用 remote_merge 功能

    $sourceurls = array(
        "http://site.com/1.pdf",
        "http://site.com/234234234.png",
        "http://site.com/archive.zip",
        "http://site.com/1f41f.anyformat",
        "http://site.com/file.txt"
    );
    
    foreach($sourceurl as $sourceurls){
        $filename = basename(parse_url($sourceurl, PHP_URL_PATH);
        $targetftp = "ftp://${ftpuser}:${ftppasswd}@${ftpserver}${ftppath}/$filename";
        remote_merge($sourceurl,$targetftp)
    }
    

    【讨论】:

      【解决方案3】:

      193 个问题,3 个答案……哇。

      function curl($url){
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_close ($ch);
          return curl_exec($ch);
      }
      
      $files = array();
      $dir = "dir/";
      
      foreach($files as $file){
          $name = explode("/", $file);
          $name = end($name);
          $contents = curl($file);
          file_put_contents($dir.$name, $contents);
      }
      

      【讨论】:

      • $name = basename(parse_url($file, PHP_URL_PATH));,否则是一个很好的答案。这样它将正确处理查询字符串和锚点。
      • 我是由给出的示例数组引导的,但你的建议很好。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多