add the contents of 2 txt files together - php

I have this small piece of code on my website that i use to count downloads.
its pretty simple really,
counter.php sends the command and counter.txt is just a 1 line text file with a number that auto goes up every time the link is clicked.
My question is, is it possible to have 2 counter.txt files and add them to a third counter.txt file? so it would look something like:
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
So essentially i want to offer 2 downloads
a light version and a full version
and then keep track of each download count separately. but then also have a count for the total of both downloads.
oh and to make sure i include enough detail, on the download.php page i echo the counter.txt file with
<?php echo file_get_contents('counter.txt');?>

Adding the counters of two files should be easy. You just have to read each file and then the variables are added and written to third counter file or whatever you desire. An example:
<?php
$first=file_get_contents("counter1.txt");
$second=file_get_contents("counter2.txt");
$sum=$first+$second;
file_put_contents("counter3.txt",$sum);
?>

So here was the end result, I had to swap around the txt files for counter.txt and urls but this worked perfectly...
$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");

Related

PHP File Handling (Download Counter) Reading file data as a number, writing it as that plus 1

I'm trying to make a download counter in a website for a video game in PHP, but for some reason, instead of incrementing the contents of the downloadcount.txt file by 1, it takes the number, increments it, and appends it to the end of the file. How could I just make it replace the file contents instead of appending it?
Here's the source:
<?php
ob_start();
$newURL = 'versions/v1.0.0aplha/Dungeon1UP.zip';
//header('Location: '.$newURL);
//increment download counter
$file = fopen("downloadcount.txt", "w+") or die("Unable to open file!");
$content = fread($file,filesize("downloadcount.txt"));
echo $content;
$output = (int) $content + 1;
//$output = 'test';
fwrite($file, $output);
fclose($file);
ob_end_flush();
?>
The number in the file is supposed to increase by one every time, but instead, it gives me numbers like this: 101110121011101310111012101110149.2233720368548E+189.2233720368548E+189.2233720368548E+18
As correctly pointed out in one of the comments, for your specific case you can use fseek ( $file, 0 ) right before writing, such as:
fseek ( $file, 0 );
fwrite($file, $output);
Or even simpler you can rewind($file) before writing, this will ensure that the next write happens at byte 0 - ie the start of the file.
The reason why the file gets appended it is because you're opening the file in append and truncate mode, that is "w+". You have to open it in readwrite mode in case you do not want to reset the contents, just "r+" on your fopen, such as:
fopen("downloadcount.txt", "r+")
Just make sure the file exists before writing!
Please see fopen modes here:
https://www.php.net/manual/en/function.fopen.php
And working code here:
https://bpaste.net/show/iasj
It will be much simpler to use file_get_contents/file_put_contents:
// update with more precise path to file:
$content = file_get_contents(__DIR__ . "/downloadcount.txt");
echo $content;
$output = (int) $content + 1;
// by default `file_put_contents` overwrites file content
file_put_contents(__DIR__ . "/downloadcount.txt", $output);
That appending should just be a typecasting problem, but I would not encourage you to handle counts the file way. In order to count the number of downloads for a file, it's better to make a database update of a row using transactions to handle concurrency properly, as doing it the file way could compromise accuracy.
You can get the content, check if the file has data. If not initialise to 0 and then just replace the content.
$fileContent = file_get_contents("downloadcount.txt");
$content = (!empty($fileContent) ? $fileContent : 0);
$content++;
file_put_contents('downloadcount.txt', $content);
Check $str or directly content inside the file

Display IMAGE OR DATA through external TXT File

I have file1.txt and A PHP Code which increment it.
I have a snippet to display the image.
I paste a snippet in my website that displays Images by reading the data number from file1.txt.
I use the snippet multiple times in one page but I get the same result. What happens is that when the website page is loaded it reads the file1.txt having ,lets say number 10, image number.
What I want is that Snippet 1 Displays 10 Increment file1.txt
then Snippet 2 Displays 11 and so on.
how should i make the snippet in such a way that it waits for the increment and then reads it and then it displays image.
Example:
Snippet 1 >10th Image
Snippet 2 >11th Image
Snippet 3 >12th Image
While all are executed in one page?
One Way i Think might be that the snippet GET the wait.txt and
checks if its 1 or 0 If It is 1 it waits for certain seconds then
execute the external php and if it is 0 it proceeds to executes the
external PHP. Then External PHP on Execution Sets wait.txt to
1 while its being used and then once it has finished it sets the
wait.txt to 0
But I doubt it will flawlessly work. I need you guys to help me out.
Okay the below code is what I have
The PHP Contains this:
$open = fopen("xml/file1.txt", "r+");
$num = fgets($open);
$close = fclose($open);
$num++;
$open = fopen("xml/file1.txt", "w+");
fwrite($open, $num);
$close = fclose($open);
The Snippet
<?php
$myFile = "../xml/file1.txt";
$line= file($myFile);//file in to an array
$image = $line[0]; //So that it Reads the first line if 2nd line has /n
echo "<img src=''.$image.'.img'></img>";
/*Executing PHP through php as it as additional code in php
which does some other verifications.*/
echo '<script src="//localhost/image.php"></script>';
?>
The file1.txt Contains:
1
//Ignore the comment here it just contain 1 number
//which increment each time the snippet executes the php
So I paste The snippet in one page Multiple times. But All snippet displays the same image instead of in ascending order. I want to find how can I do it? No MySql Database. And I don't want to list and read each line.
I want my snippet to read the data from file1.txt after it has been
updated
I want my snippet to know that the php is busy and needs to wait while other snippet is using it. As my project will include heavy traffic I want it Optimized.
Lastly I am a new to this so it's hard to figure out.
THE CODE BELOW WORKS BUT HOW CAN I OPTIMISE IT for heavy traffic?
<?php
session_start();
waitque();
function waitque() {
$input = $_SERVER['HTTP_HOST'];
$e = $_SERVER['REQUEST_URI'];
$ip = $_SERVER['REMOTE_ADDR'];
$input = trim($input, '/');
// If not have http:// or https:// then prepend it
if (!preg_match('#^http(s)?://#', $input)) {
$input = 'http://' . $input;
}
$urlParts = parse_url($input);
// Remove www.
$dom = preg_replace('/^www\./', '', $urlParts['host']);
if(isset($_SESSION['worker'])){
$open = fopen("queue/imageindex.txt", "r+");
$value = fgets($open);
$close = fclose($open);
$value++;
$open = fopen("queue/imageindex.txt", "w+");
fwrite($open, $value); // variable is not restated, bug fixed.
$close = fclose($open);
$myFile = "queue/imageindex.txt";
$line= file($myFile);//file in to an array
$relid = $line[0];
echo $relid." Code PUBLISHED</div>";
unset($_SESSION['worker']);
} else {
echo "<div>waiting...</div>";
$_SESSION['worker']= $dom.$a.$ip;
waitque();
}
}
?>

What is wrong with my fopen() PHP

I've got this variable which I want to save which is:
$counter = $counter['counter']++;
to make it so that it increments when I refresh the page.
Therefore, I decided to use the fopen, override the $counter variable and then save it.
I am still a beginner and I do not know how the fopen, fgets, fclose works.
So I wrote something like this.
$fp = fopen("file.php","r");
fwrite($fp, $counter);
fclose($fp);
So I wanted to open the file(file.php)(the file which is I am writing this code FYI), and then override the variable after it had been incremented and then save it by closing.
But the code doesn't seem to want to work and the variable does not seem to want to increment.
What am I doing wrong?
Do I want to have this $counter in a different file and pull the variable from there.
FYI: I don't want to use session_start() and $_SESSION because I am using cron job and it will not work.
EDIT
$result = mysql_query('SELECT MIN(ID) AS min, MAX(ID) AS max FROM ytable') or exit(mysql_error());
$row = mysql_fetch_assoc($result);
if($counter['counter'] < $row['max']){
if (isset($counter['counter'])){
$counter = $counter['counter']++;
}else{
$counter = $counter['counter'] = 0;
}
}
This is more of the code for those who are confused
You could read file like this. Open the file with previous counter & fetch the counter, increment it like this
$counter = readfile("file.php");
$counter++;
To write to the file, open the file in write mode like this
$fp = fopen("file.php","w");
fwrite($fp, $counter);
fclose($fp);
Is that result you are looking for ?
As chris85 suggested, database is used for this kind of cases. Better to use database instead of file handling.
So say you have file.txt and that contains 5. In that same directory you have script.php; this file would have
$counter = file_get_contents('file.txt'); // this takes in whatever value is in the file e.g in this case '5'
$counter++; // increment the value by 1 so we are now at 6
file_put_contents('file.txt', $counter); //write the value '6' back to the file
file.txt would then have 6, after the first load.

PHP using fopen to download txt file via URL. How to limit the amount to download?

I have written a php script which parses this text file
http://www.powerball.com/powerball/winnums-text.txt
Everything is good, but I wish to control the amount that is download i.e. I do not need every single result maybe max the first 5. At the moment I am downloading the entire file (which is a waste of memory / bandwidth).
I saw the fopen has a parameter which supposed to limit it but whatever value I placed in has no effect on the amount of text that is downloaded.
Can this be done? Thank you for reading.
Here is a small snippet of the code in question which is downloading the file.
<?php
$file = fopen("http://www.powerball.com/powerball/winnums-text.txt","rb");
$rows = array();
while(!feof($file))
{
$line = fgets($file);
$date = explode("Draw Date",$line);
array_push($rows,$date[0]);
}
fclose($file);
?>
Thanks everyone this is the code which just downloads the first row of results
while(!feof($file))
{
$line = fgets($file);
$date = explode("Draw Date",$line);
array_push($rows,$date[0]);
if(count($rows)>1)
{
break;
}
}
fclose($file);
You can break whenever you don't need more data. In this example when count($rows)>100
while(!feof($file)) {
$line = fgets($file);
$date = explode("Draw Date",$line);
array_push($rows,$date[0]);
if (count($rows)>100)
break;
}
The issue is that your while condition is only met once you've read through to the end of the file. If you only want to get the first N lines you'll need to change that condition. Something like this might help get you started:
$lineCountLimit = 5;
$currentLineCount = 0;
while($currentLineCount < $lineCountLimit)
{
$line = fgets($file);
$date = explode("Draw Date",$line);
array_push($rows,$date[0]);
$currentLineCount++;
}
Please try the following recipe to download only a part of the file, like 10 KBytes first, then split to lines and analyze them. How to partially download a remote file with cURL?

Writing some data to a specific area within a file in PHP

I'm experimenting with fopen for the first time and was wondering if it was possible to search for a particular section within a file before adding or replacing that content with data?
Ideally, I'd like to:
Use fopen to get the file
Search for a comment called <!-- test -->
Replace that comment with new data.
This possible? (for the record - Appending data to the end of the file or adding new data to a specific line number would not work for what I'm working on as the file is constantly changing).
Thanks!
<?php
// make sure radio is set
if( isset($_POST['enableSocialIcons']) )
{
// Open file for read and string modification
$file = "/test";
$fh = fopen($file, 'r+');
$contents = fread($fh, filesize($file));
$new_contents = str_replace("hello world", "hello", $contents);
fclose($fh);
// Open file to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_contents);
fclose($fh);
}
?>
From: http://www.php.net/manual/en/function.fopen.php#81325
EDIT: To see what exactly is getting sent by your form do this at the top of the PHP file you're posting to:
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
exit;
?>
If you read the entire file in then use something str_replace to make the change, you should be able to get what you want.

Categories