php 下载附件并更新下载次数

这段代码不知道是什么原因,执行的时候实际下载次数不是 +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);
?>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值