简体   繁体   English

为什么此PHP下载脚本不起作用?

[英]Why Doesn't This PHP Download Script Work?

Here is a simple script I have written to limit downloads for users to one at a time (IE if they are downloading a file then they cannot download another one until they cancel the current download or it finishes). 这是我编写的一个简单脚本,用于限制用户一次只能进行一次下载(即,如果他们正在下载文件,则他们必须先取消当前下载或下载完成,才能下载另一个文件)。

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);
}

When I test it out, it works fine, but for a lot of people, their IP never gets cleared out of the database - even when they have finished downloading/cancelled a file. 当我对其进行测试时,它可以正常工作,但是对于许多人来说,即使从他们完成下载/取消文件操作后,他们的IP也不会从数据库中清除。 Why don't the IPs get deleted? 为什么不删除IP?

问题是,随着下载量的增加,MySQL连接消失了,我只需要在clear_downloader函数中重新连接即可,现在一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM