下载计数并在php中显示文件大小


download count and show file size in php

我有一个脚本,可以上传用户可以下载的pdf文件。

现在我想显示下载计数和文件大小(MB)。

我也希望得到一些帮助来避免任何可能的攻击,因为我的脚本非常简单。

我的download.php如下

<?php
    include("admin/config.php");
    $id   = $_REQUEST['id'];
    $sql  = "SELECT * FROM novels  where id=$id";
    $rs   = mysql_query($sql);
    $row  = mysql_fetch_array($rs);
    $pdf  = $row['pdf'];
    $name = $row['title'];
    $path = 'admin/';
    $file = $path.$pdf;
    $filename = $pdf;
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename='$name-bookspk.net.pdf'");
    header("Content-Length: filesize($file)");
    readfile($file);
    ?>

对于下载计数,您可以保存到数据库

$sql = "UPDATE `novels` SET `count`=`count`+1 WHERE `id`=".(int)$id;

假设你有一个计数列

对于下载大小,您应该将filesize移出:

header("Content-Length: ".filesize($file));

这是为了让浏览器看到进度,如果你想显示它,它是一样的,你可以将它存储在数据库中

$sql = "UPDATE `novels` SET `size`=".filesize($file)." WHERE `id`=".(int)$id;

这应该在上传时设置。

由于存在漏洞,请记住对mysql查询进行转义。对于整数很简单,因为您可以强制转换(int)

尝试添加缓存头,如果您担心误报,这将减少从服务器下载文件的次数。

<?php
header("Expires: Sat, 26 Jul 2020 05:00:00 GMT"); // Date in the future
?>

上传文件时,您可能应该将文件大小存储在表中,这样您就可以通过对数据库的一次调用来获取所有信息。