这段代码不知道是什么原因,执行的时候实际下载次数不是 +1 而是 +2。
在这段代码下面有一个改进的,下载次数只 +1。
<?php
require_once('./login.php');
downloadAttachment();
// 下载附件
function downloadAttachment() {
global $conn;
// 得到 id
$id = $_REQUEST['file_id'];
// 查询数据库
$attachUrl = "";
$attachSql = "SELECT ming,url, downloadnum FROM articleattach WHERE id='$id'";
$result = $conn->Execute($attachSql);
if ($result) {
$attachUrl = $result->fields['url'];
$attachMing = $result->fields['ming'];
$downloadnum = $result->fields['downloadnum'] + 1;
// 下载附件
downloads($attachMing, $attachUrl, $downloadnum, $id);
}
}
function downloads($name, $dir, $downloadnum, $id){
global $conn;
if (!file_exists($dir)) {
// 没有找到文件
header("Content-type: text/html; charset=utf-8");
echo "File not found!";
exit;
} else {
// 下载文件
$file = fopen($dir,"r");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($dir));
Header("Content-Disposition: attachment; filename=".$name);
echo fread($file, filesize($dir));
fclose($file);
// 更新数据库
//echo "UPDATE articleattach SET downloadnum='$downloadnum' WHERE id='$id'";
$attachSql = "UPDATE articleattach SET downloadnum='$downloadnum' WHERE id='$id'";
$conn->Execute($attachSql);
}
}
?>
改进后的:
attachDownLoad.php
<?php
require_once('./login.php');
header("Content-type: text/html; charset=utf-8");
downloadAttachment();
// 下载附件
function downloadAttachment() {
global $conn;
// 得到 id
$id = $_REQUEST['file_id'];
// 查询数据库
$attachUrl = "";
$attachSql = "SELECT ming,url, downloadnum FROM articleattach WHERE id='$id'";
$result = $conn->Execute($attachSql);
if ($result) {
$attachUrl = $result->fields['url'];
$attachMing = $result->fields['ming'];
$downloadnum = $result->fields['downloadnum'] + 1;
// 下载附件
downloads($attachMing, $attachUrl, $downloadnum, $id);
}
}
function downloads($name, $dir, $downloadnum, $id){
global $conn;
if (!file_exists($dir)) {
// 没有找到文件
echo "File not found!";
exit;
} else {
// 更新数据库
$attachSql = "UPDATE articleattach SET downloadnum='$downloadnum' WHERE id='$id'";
$conn->Execute($attachSql);
// 跳到真正的下载页面
header("location:downloadfile.php?name=$name&dir=$dir");
}
}
?>
downloadfile.php
<?php
require_once('./login.php');
$dir = $_REQUEST['dir'];
$name = $_REQUEST['name'];
// 下载文件
$file = fopen($dir,"r");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($dir));
Header("Content-Disposition: attachment; filename=".$name);
echo fread($file, filesize($dir));
fclose($file);
?>