首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么这个PHP下载脚本不起作用?

为什么这个PHP下载脚本不起作用?
EN

Stack Overflow用户
提问于 2013-08-28 09:33:08
回答 1查看 119关注 0票数 0

这是我写的一个简单的脚本,用来限制用户一次只能下载一个(如果他们正在下载一个文件,那么他们不能下载另一个文件,直到他们取消当前的下载或下载完成)。

代码语言:javascript
复制
ignore_user_abort(true);

$local_file = $_GET['filename'];
$download_file = explode("/", $local_file);
$download_file = $download_file[count($download_file) -1];

// set the download rate limit (value is in kilobytes per second
$download_rate = 100;
if(file_exists($local_file) && is_file($local_file)) {
    $ip = visitor_ip();
    if(!are_downloading($ip)) {
        header('Cache-control: private');
        header('Content-Type: application/octet-stream');
        header('Content-Length: '.filesize($local_file));
        header('Content-Disposition: filename='.$download_file);

        flush();

        $file = fopen($local_file, "r");
        log_downloader($ip);

        while(!feof($file)) {
            if (!connection_aborted()) {
            // send the current file part to the browser
            print fread($file, round($download_rate * 1024));
            // flush the content to the browser
            flush();
            // sleep one second
            sleep(1);
        } else {
            break;
            }
        }

        clear_downloader($ip);      
        fclose($file);
    } else {
        die('<span style="color:#DDDDDD">Due to server limitations you may only download one file at a time. Please cancel or wait for your current download to finish before trying again. Click <a href="/simfiles">here</a> to return.</span>');
    }
} else {
    die('Error: The file '.$local_file.' does not exist!');
}

function visitor_ip() { 
    if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $TheIp=$_SERVER['HTTP_X_FORWARDED_FOR'];
    else $TheIp=$_SERVER['REMOTE_ADDR'];

    return trim($TheIp);
}

function are_downloading($ip) {
    $query = "select * from downloaders where ip_addr='$ip'";
    $result = mysql_query($query);

    $num_rows = mysql_num_rows($result);

    return $num_rows > 0; 
}

function log_downloader($ip) {
    $query = "insert into downloaders (ip_addr) values ('$ip')";
    $result = mysql_query($query);
}

function clear_downloader($ip) {
    $query = "delete from downloaders where ip_addr='$ip'";
    $result = mysql_query($query);
}

当我测试它时,它工作得很好,但对于许多人来说,他们的IP地址永远不会从数据库中清除-即使他们已经完成下载/取消文件。为什么IP没有被删除?

EN

回答 1

Stack Overflow用户

发布于 2013-08-28 11:46:09

问题是,在大量下载的情况下,MySQL连接消失了,我只需在clear_downloader函数中重新连接,现在它工作得很好。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18478040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档