Hello guys!


I want to make a viewer function that adds up everytime the script runs.

I want to do it with a text file, something like this i guess..

$fp = fopen("video1.txt", 'a');

        ///I guess i need to get the current value of the file, then add an additional view point somehow.
	fwrite($fp, "What do i do here?  +1 on what?");
	fclose($fp);

I would love you for a thousand years if u wrote this little thing as it should.

/Regards, Sorcher

Recommended Answers

All 3 Replies

<?php function incrementCounter($counterFile) { //INCREMENT THE COUNTER
	$current=readCounter($counterFile);
	$current++;
	if(!$handle = fopen($counterFile, "w")) { return false; }
	else { if(fwrite($handle, $current) === FALSE) { return false; } }
	fclose($handle);
	return true; }
function readCounter($counterFile) { //OUTPUT THE CURRENT COUNT
	$contents=file_get_contents($counterFile);
	if(is_numeric((int)$contents)) { return ((int)$contents); }
	else { return 0; } }
$counterFile="video1.txt";
incrementCounter($counterFile); //INCREMENT THE COUNTER
echo readCounter($counterFile); //OUTPUT THE CURRENT COUNT
?>

There is another simpler way to do this:

$content = 'I want to add this line at the end of text file.';
$filePath = 'sometext.txt';

// THIS CODE FIRST OPENS THE FILE, APPENDS CONTENT TO IT AND THEN WRITES IT BACK
file_put_contents($filePath, file_get_contents($filePath) . $content);

Or in your case:

$filePath = 'sometext.txt';

// THIS CODE FIRST OPENS THE FILE, APPENDS CONTENT TO IT AND THEN WRITES IT BACK
file_put_contents($filePath, intval(file_get_contents($filePath)) + 1);

Thanks guys! I'll try both options and flag as solved as soon as i got it working, peace

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.