JamesS1
JamesS1

Reputation: 39

How to increment a single number in a text file with PHP

I am writing a VoteBox (like/dislike box) in html and I cannot find how to do this anywhere.

Basically, there will be a like and a dislike button. When one of them gets clicked, it will forward the user to a page. And in that, I want some PHP code that will increase the number in upvotes.txt/downvotes.txt

I have tried doing it with a database but the problem is I want anyone to be able to use this without any setup.

i also want the front page to display the number of upvotes and the number of downvotes

so its kinda like this (most of this isn't real code BTW im new to PHP):

//this is the code for upvote.html
$upvotes = get_data_from_TXT_file

$changedupvotes = $upvotes + 1

set_data_in_txt_file_to_$changedupvotes

Sorry if i havent explained this very well

Any help appreciated

Upvotes: 2

Views: 2955

Answers (2)

Amal Murali
Amal Murali

Reputation: 76656

You can use file() to read the file into an array, and then increment the upvotes, and then write the data back using file_put_contents():

if (file_exists('upvotes.txt')) {

    $content = file('upvotes.txt'); // reading all lines into array
    $upvotes = intval($content[0]) + 1; // getting first line
    file_put_contents('upvotes.txt', $upvotes); // writing data

} else {

    // handle the error appropriately

}

Upvotes: 3

anubhava
anubhava

Reputation: 785246

This is skeleton of the code that you can use:

$file = 'file.txt'; // your file name
// error handling etc to make sure file exists & readable

$fdata = file_get_contents ( $file ); // read file data

// parse $fdata if needed and extract number
$fdata = intval($fdata) + 1;

file_put_contents($file, $fdata); // write it back to file

Reference:

Upvotes: 3

Related Questions