Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将2个txt文件的内容添加到一起_Php_File - Fatal编程技术网

Php 将2个txt文件的内容添加到一起

Php 将2个txt文件的内容添加到一起,php,file,Php,File,我的网站上有一小段代码,用来计算下载量。 其实很简单,, counter.php发送命令,counter.txt只是一个1行文本文件,带有一个数字,每次单击链接时自动递增 我的问题是,是否可以有2个counter.txt文件并将它们添加到第三个counter.txt文件中?所以它看起来像: counter.txt+counter2.txt=counter3.txt $counter = 'counter.txt'; $download = 'downloadurlhere'; $number

我的网站上有一小段代码,用来计算下载量。 其实很简单,, 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页面上,我用

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

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

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

最后的结果是,我不得不将txt文件交换为counter.txt和URL,但这非常有效

$count = 'counterfull.txt';
$total = 'total.txt';
$download = 'URL';

$number1 = file_get_contents($count);
$number1++;
$fh = fopen($count, w);
fwrite($fh, $number1);
fclose($fh);
$number2 = file_get_contents($total);
$number2++;
$fh = fopen($total, w);
fwrite($fh, $number2);
fclose($fh);

header("Location: $download"); 

当然只需获取两个文件的内容,然后写入一个新文件。。。这对我没有帮助,因为这正是我要问的,你试过$first=file\u get\u contents('file1.txt'),$second=file\u get\u contents('file2.txt'),然后是$third=$first+$second;文件内容(“newfile.txt”,$third)?这种方法不是并发安全的,如果两个或两个以上的人同时尝试投票,数字将不准确,实际上只有一个人会计算。使用flock()和LOCK_EX来修复它。说真的,如果10个人同时投票,此代码将只计算其中1人,您将失去9票。这是一个将失去0票的安全版本:-谷歌
线程安全
如果你想了解原因。呃,我应该说
谷歌竞速条件如果你想了解原因
,你的代码有竞速条件错误。如果两人或两人以上同时尝试投票,这种方法不是并发安全的,这些数字并不准确,实际上只有1个会算数。使用flock()和LOCK_EX来修复它。说真的,如果10个人同时投票,此代码将只计算其中1人,您将失去9票。以下是一个将失去0票的安全版本:
$lock1=fopen(“counter1.txt”、“rb”)$lock2=fopen(“counter2.txt”、“rb”)$lock2=fopen(“counter3.txt”、“rb”);羊群($lock1,LOCK_EX);羊群($lock2,LOCK_EX);羊群($lock3,LOCK_EX)$first=文件获取内容(“counter1.txt”)$第二个=文件获取内容(“counter2.txt”)$总和=$first+$second;文件内容(“counter3.txt”,$sum);羊群($lock1,LOCK_UN);羊群($lock2,LOCK_UN);羊群($lock3,LOCK_UN);fclose(1美元);fclose(2美元);fclose(3美元)
google
race condition
如果您想了解原因