2011-10-01 43 views
2

我嘗試使用PHP來強制圖片JPG文件下載,我ETH下面的代碼來實現:文件損壞時,點擊下載鏈接

HTML

<a href = "filedownload.php?src=uploads/myimage.jpg&download=true>download this file</a> 

的download.php

<?php 
ob_start(); 
include_once 'functions.php'; 

if (isset($_GET['download']) && $_GET['download'] == 'true') 
    {  

    $src = sanitizeString($_GET['src']); 
    header('Content-Description: File Transfer'); 
    header('Content-Type: image/jpeg'); 
    header('Content-Disposition: attachment; filename='.basename($src)); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: public'); 
    header('Pragma: public'); 

    } 

?> 

假設圖像的完整路徑是「www.example.com/smith/topic/uploads/myimage.jpg」,我已經收到了正確的圖像名稱,同時也出現了下載窗口,但圖像已損壞,並且1KB大小,任何人都可以告訴我爲什麼,非常感謝。

+0

什麼是裏面的文件?我敢打賭,啤酒中有一個PHP錯誤信息,它解釋了哪裏出了問題。 –

+0

哪個代碼?這是我得到的所有部分 – smith

+0

首先,在PHP腳本的開頭有一個空格,這是一個不允許的。你也忘了「在你的href結尾,你甚至會在那裏打印文件內容嗎?PS:我強烈推薦處理這樣的文件,潛在攻擊的地方太多了 –

回答

6

在這裏,你是示例演示如何使用ReadFile函數

<?php 
$file = 'monkey.gif'; 

if (file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename='.basename($file)); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($file)); 
    ob_clean(); 
    flush(); 
    readfile($file); 
    exit; 
} 
?> 
1

您需要一些實際上通過文件發送的代碼。見例如readfilefpassthru

+0

你能告訴我我應該寫什麼代碼 – smith

+0

爲什麼這會被低估? –

+0

@smith將它放在最後一個大括號之前您可能還想檢查該文件是否確實存在於目錄中,只要攻擊者使用你的腳本去讀取它之外的東西(例如'/../../../../etc/passwd') –

1

嘗試使用:

header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";");