PHP下载图像脚本不起作用

时间:2012-07-27 08:01:23

标签: php

我正在使用以下代码将图像下载到我的硬盘。通过使用我放在新闻页面中的第一个链接,可以使用.i可以下载图像。我放在画廊中的第二个链接,不起作用。路径是正确的,我打开了一个没有downlaod.php文件的图像,路径中没有错误,但图像没有下载。我使用不同的图像ID尝试了不同的图像,但它不适用于那个特定的页面

<a href="<?php echo SITE; ?>download.php?filename=<?php echo SITE; ?>uploads/news/<?php echo $rowimg['image']; ?>" title="download">

下载图像

 <a href="<?php echo SITE; ?>download.php?filename=<?php echo SITE; ? >uploads/gallery/<?php echo $row['folder']; ?>/<?php echo $row1['folder']; ?>/<?php echo  $row2['folder']; ?>/<?php echo $rowimg['image']; ?>" title="Download">
download</a> 

错误是:文件可能已损坏或太大

的download.php

<?php    
$filename = $_GET["filename"];
$buffer = file_get_contents($filename);
/* Force download dialog... */
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Type: application/image");

/* Don't allow caching... */
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

/* Set data type, size and filename */
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($buffer));
header("Content-Disposition: attachment; filename=$filename");

/* Send our file... */
echo $buffer; 
?> 

1 个答案:

答案 0 :(得分:1)

使用cURL

$ch = curl_init('http://my.image.url/photo.jpg');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // buffer output (`true` if you will be redirecting stream to the user, in $result will be your image content)
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); // because image is binary data

// Within these two lines you can donwload image directly to the file on your server
// $fp = fopen('/my/saved/image.file', 'w');
// curl_setopt($ch, CURLOPT_FILE, $fp);

$result = curl_exec($ch); // executing requrest (here will be raw image data if RETURNTRANSFER == true)
$response_code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); // getting response code to ensure that request was successfull
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); // getting return content-type

// Listing allowed image types    
$allowed_mimes = array(
            'image/jpeg',
            'image/gif',
            'image/png'
            );

if ($response_code == 200 AND in_array($content_type, $allowed_mimes) ) {
  header( 'Content-Type: '.$content_type );
  echo $result; // echoing image to STDOUT
} else
  return false;