2010-07-27 84 views
0

我开发了一个网页,我想创建一个下载部分。我有一个PHP代码来下载文件,但我已经尝试了很多次,但它不起作用。我继续看到错误消息,但picture.jpg文件与download.php和index.php位于同一目录中。我不知道问题是什么。文件下载与php到网页

的download.php中的含量:在index.php的

<?php 


if (isset($_GET[‘file’]) && basename($_GET[‘file’]) == $_GET[‘file’]) { 

$filename = $_GET[‘file’]; 

} else { 

$filename = NULL; 

} 


$err = ‘<p style="color:#990000">Sorry, the file you are requesting is unavailable.</p>’; 

if (!$filename) { 


echo $err; 

} else { 


$path = ‘downloads/’.$filename; 


if (file_exists($path) && is_readable($path)) { 


$size = filesize($path); 
header('Content-Type: application/octet-stream'); 
header('Content-Length: '.$size); 
header('Content-Disposition: attachment; filename='.$filename); 
header('Content-Transfer-Encoding: binary'); 


$file = @ fopen($path, ‘rb’); 

if ($file) { 


fpassthru($file); 
exit; 

} else { 

echo $err; 

} 

} else { 

echo $err; 

} 

} 

?> 

内容:

<a href="download.php?file=picture.jpg">Download file</a> 
+0

你看到了什么错误信息? – ankitjaininfo 2010-07-27 20:54:13

回答

0

file_exists()is_readable()不喜欢的相对路径。改用绝对路径。

你也许可以使用$path = $_SERVER['DOCUMENT_ROOT'] . "/$filename";

+0

我试过这个:$ path = $ _SERVER {'DOCUMENT_ROOT'}。 “/ $ filename”,但不幸的是错误是一样的 – DaveDetent 2010-07-27 21:12:03

1

我觉得人物都拧了。尝试用正常的单引号替换它们('),并在从别人的博客复制代码时更加小心。 ;)

0

我使用下面的代码为我的应用程序,它适用于我。

if(file_exists($path . $file)){ 
    header("Content-type: application/octet-stream"); 
    header("Content-Disposition: attachment; filename=\"" . $file . "\""); 
    header("Content-Length: " . filesize($path . $file)); 
    readfile(base64_decode($path . $file); 
}else{ 
    // No file, do something