2011-11-07 37 views
0

嗨我有這段代碼但沒有發生,任何想法? 當我運行這個頁面時,我得到了一個空白頁面,我不明白的一件事是文件名只是名稱而沒有整個地址。 URL是這樣的,有完整的地址:Php頭部力量下載 - 不起作用

http://site.com/download_orig.php?file=prod_media/images/neografik_pty_ltd/product_test_10/192027102011_istock_000016116673xsmall.jpg

乾杯,男

<?php 

$filename = $_GET['file']; 
if (!is_file($filename)) { 
    header('Location: home.php'); exit; 
} 
$filepath = str_replace('\\', '/', realpath($filename)); 
$filesize = filesize($filepath); 
$filename = substr(strrchr('/'.$filepath, '/'), 1); 
$extension = strtolower(substr(strrchr($filepath, '.'), 1)); 
switch($extension) { 
    case "pdf": $mime="application/pdf"; break; 
    case "rvt": $mime="application/octet-stream"; break; 
    case "rft": $mime="application/octet-stream"; break; 
    case "rfa": $mime="application/octet-stream"; break; 
    case "xls": $mime="application/vnd.ms-excel"; break; 
    case "xlsx": $mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break; 
    case "dwg": $mime="application/acad"; break; 
    case "dwf": $mime="application/acad"; break; 
    case "gif": $mime="image/gif"; break; 
    case "png": $mime="image/png"; break; 
    case "jpeg": 
    case "jpg": $mime="image/jpg"; break; 
    default: $mime=0; 
} 

// use this unless you want to find the mime type based on extension 
// $mime = array('application/octet-stream'); 

// Only allowed files here, no hack and stuff, sorry 
if($mime===0) header('Location: home.php'); exit; 

header('Content-Description: File Transfer'); 
header('Content-Type: '.$mime); 
header('Content-Disposition: attachment; filename='.basename($filename)); 
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Content-Length: '.sprintf('%d', $filesize)); 

// check for IE only headers 
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)) { 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
} else { 
    header('Pragma: no-cache'); 
} 
ob_clean(); 
flush(); 
readfile($filename); 
exit; 
?> 

回答

1

你有

if($mime===0) header('Location: home.php'); exit;

出口總是被調用(即使$ mime不爲零)導致程序終止。這樣做:

if($mime===0) { header('Location: home.php'); exit; }

+0

Tks! Vikk,現在正在保存,但當我嘗試打開圖像時,我得到了這個:無法打開文件。它可能已損壞或者Preview無法識別的文件格式。 – Mango

+0

有人認爲我不明白的是在標題中只是圖片的名稱,沒有告訴正確的文件夾,它是如何工作的? – Mango

+0

而不是'readfile($ filename);'你應該做'readfile($ filepath);'它會正確下載。 – Vikk