首页 > 解决方案 > 将2个txt文件的内容加在一起

问题描述

我的网站上有一小段代码,用于计算下载量。它非常简单,counter.php 发送命令,counter.txt 只是一个 1 行文本文件,每次单击链接时都会自动增加一个数字。

我的问题是,是否可以有 2 个 counter.txt 文件并将它们添加到第三个 counter.txt 文件中?所以它看起来像: counter.txt + counter2.txt = counter3.txt ?

$counter = 'counter.txt'; 
$download = 'downloadurlhere';

$number = file_get_contents($counter); // read count file 
$number++; // increment count by 1 
$fh = fopen($counter, 'w'); // open count file for writing 
fwrite($fh, $number); // write new count to count file 
fclose($fh); // close count file 
header("Location: $download"); // get download 

所以基本上我想提供 2 次下载一个轻量版和一个完整版

然后分别跟踪每个下载计数。但随后也要计算两次下载的总数。

哦,为了确保我包含足够的细节,在 download.php 页面上,我回显了 counter.txt 文件

<?php echo file_get_contents('counter.txt');?>

标签: phpfile

解决方案


添加两个文件的计数器应该很容易。您只需读取每个文件,然后将变量添加并写入第三个计数器文件或您想要的任何文件。一个例子:

<?php
$first=file_get_contents("counter1.txt");
$second=file_get_contents("counter2.txt");
$sum=$first+$second;
file_put_contents("counter3.txt",$sum);
?>

推荐阅读