自动从任何URL位置下载图像

问题描述 投票:6回答:1

在我正在进行的项目的后期阶段,我遇到了一个严重的问题:

我编写了一个PHP函数,使用户可以通过单击其链接在硬盘上自动下载图像。但这很容易,因为图像上传到网站服务器,我知道它是完整的服务器地址。例如:"home/clients/websites/w_apo/public_html/wp-content/uploads/image.jpg"

但现在客户希望能够从他自己的地址http://www.something.com/image.jpg粘贴图像URL,并且仍然能够通过单击前端上的链接自动下载该图像。

我在这个编程领域有点新意,所以我真的需要你的帮助。任何链接,建议,资源都是最受欢迎的。

谢谢!

这是我目前的下载功能:

download_file($_GET['file']);

/******************************************************************/

function download_file( $fullPath ){

  // Must be fresh start
  if( headers_sent() )
    die('Headers Sent');

  // Required for some browsers
  if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

  // File Exists?
  if( file_exists($fullPath) ){

    // Parse Info / Get Extension
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);

    // Determine Content Type
    switch ($ext) {
      case "pdf": $ctype="application/pdf"; break;
      case "exe": $ctype="application/octet-stream"; break;
      case "zip": $ctype="application/zip"; break;
      case "doc": $ctype="application/msword"; break;
      case "xls": $ctype="application/vnd.ms-excel"; break;
      case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
      case "gif": $ctype="image/gif"; break;
      case "png": $ctype="image/png"; break;
      case "jpeg":
      case "jpg": $ctype="image/jpg"; break;
      default: $ctype="application/force-download";
    }

    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$fsize);
    ob_clean();
    flush();
    readfile( $fullPath );

  } else
    die('File Not Found');

}
php download http-headers
1个回答
13
投票

你有几个选择。 #1使用file_get_contents。这不是最好的方式,但它会起作用。

<?php
//Get the file
$content = file_get_contents("http://example.com/image.jpg");


//Store in the filesystem.
$fp = fopen("/location/to/save/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
?>

选项#2使用cURL:

See this example

© www.soinside.com 2019 - 2024. All rights reserved.