在php中下载文件时防止多个连接

时间:2014-04-10 07:44:50

标签: php codeigniter

有一个允许用户下载文件的PHP function download()。解密的文件在服务器上创建,并使用readfile($file)提供给用户。但是当 Internet Download Manager 使用多个连接下载它时,它会建立多个连接,并且在服务器上多次创建该文件,每个连接一个。即使有多个下载请求,为单个用户创建一个文件的最佳解决方案也是什么。下载后也应删除。 以下是下载示例代码。

public function download($new_filename,$original_filename){
    $fp2=fopen($new_filename,'wb'); //create empty file name $new_filename
    fputs($fp2,base64_decode(file_get_contents($original_filename)));//decoding and writing to $fp2

    header('Content-Description: File Transfer');
    header("Content-Type: application/".$ext);
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Disposition: attachment; filename="' . $new_filename . '"');
    header("Content-Length: " . filesize($new_filename));
    ob_clean();
    flush();
    readfile($new_filename);

    /***** removing temporary decoded file ****/
    if(file_exists($new_filename)) {
        chmod($new_filename,0777); //Change the file permissions if allowed read and write and execute
        unlink($new_filename); //remove the file
    }
    fclose($fp2);
}

2 个答案:

答案 0 :(得分:0)

我想最简单的方法就是这样:

生成具有“票证”的唯一下载URL,该票证允许一次访问该文件(例如dl.php?file=ABC123&ticket=1231292),在生成此票证时将其存储在数据库或其他结构中,以便您可以使其无效下载开始的时候。

在下载脚本中,检查ticketid是否有效,如果不是,则以500 HTTP状态响应。 如果它有效,则开始生成文件等,使票证无效,然后开始将文件发送给客户端。

答案 1 :(得分:0)

也许您可以使用base64_decodefile_get_contents代替readfile,例如:

public function download($new_filename,$original_filename) {

    header('Content-Description: File Transfer');
    header("Content-Type: application/".$ext);
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Disposition: attachment; filename="' . $new_filename . '"');
    header("Content-Length: " . filesize(base64_decode(file_get_contents($original_filename))));

    echo base64_decode(file_get_contents($original_filename));

}

您可以使用$_SERVER['REMOTE_ADDR']

添加一些内容以通过IP地址锁定1个连接