通过php脚本下载文件

时间:2013-07-03 07:00:51

标签: php download

我刚刚从000webhost(免费)切换到godaddy(付费)服务器,到目前为止,它比000webhost>还差10倍。>

无论如何,我的问题在于下载。我使用以下代码,它在000webhost上正常工作,允许用户下载rar文件,但现在在godaddy上,rar文件将返回归档结束错误。我通过FTP检查,文件没有通过上传损坏

<?php
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$IP1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
$IP2 = $_SERVER['REMOTE_ADDR'];
$HWID = $_GET['HWID'];
date_default_timezone_set('America/New_York');
$date = date("m/d/y g:i:sA", time());
$file = $_GET['file'];

file_put_contents('Logs/Downloaded.txt', "IP: " . $IP2 . " Downloaded On: " . $date . " File: " . $file . " User Agent: " . $userAgent . "\n", FILE_APPEND);



$path = "files/";
$fullPath = $path.$file;

if(file_exists($fullPath)){
if ($fd = fopen ($fullPath, "r")) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-type: application/pdf"); // add here more headers for diff. extensions
        break;
        case "zip":
        header("Content-type: application/zip");
    break;
        default;
        header("Content-type: application/octet-stream");
    }
    header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
    ob_flush();
        flush(); 
    }
}
fclose ($fd);
exit;
}else{
    die("File could not be found");
}
?>

1 个答案:

答案 0 :(得分:0)

脚本是否完整?您可能需要set_time_limit(0)才能确保完成。

另一件事是在十六进制编辑器中打开下载的文件并查找异常 - 我怀疑你可能在那里有一个PHP警告。你在输出循环中调用ob_flush,但据我所知,你没有执行任何输出缓冲。它可能会触发警告,从而破坏您的输出。