成功下载后如何更新数据库


how to update the database upon successful downloading?

我已经编写了一个下载脚本,它将从目录中下载文件。成功下载后,我需要更新数据库,所以我编写了以下代码。

$path = $_SERVER['DOCUMENT_ROOT']."/upload/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
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
        header("Content-Disposition: attachment; filename='"".$path_parts["basename"]."'""); // use 'attachment' to force a download
        break;
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: 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;
    }
}
fclose ($fd);
$update = mysql_query("Update query");
if($update) {
echo "updated";
}
else {
echo 'error'.mysql_error();
}
exit;
但是当我单击下载链接并在弹出窗口中出现浏览器弹出窗口时,当我单击取消按钮时,它不应该执行更新查询,

因为文件未下载,但是在使用上述代码时,即使我单击取消按钮,也会执行更新查询。

那么我的代码中有什么错误呢?

您需要检查用户是否中止了请求,如果没有,则仅插入行。

if (connection_status() == CONNECTION_NORMAL) {
    // do query here
}

看:

  • http://www.php.net/manual/en/function.ignore-user-abort.php
  • http://www.php.net/manual/en/function.connection-status.php
  • http://www.php.net/manual/en/function.connection-aborted.php