Jump to content

[SOLVED] open a text file, get number, add to it and close it.


jjmusicpro

Recommended Posts

i am having trouble with this...

 

i wanted to open a text file c.txt, get the number thats in there, add to it, and close the file

 

here is what i have

 

<?php

$file = fopen("c.txt", "r") or exit("Unable to open file!");

//Output a line of the file until the end is reached

while(!feof($file))

  {

  echo "NUMBER -".fgets($file). "<br />";

 

  }

fclose($file);

?>

Link to comment
Share on other sites

<?php
$file = fopen("c.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
   $num = fgets($file); 
  }
fclose($file);

$file = fopen("c.txt", "w");
fwrite($file, $num+1);
fclose($file);

?>

Link to comment
Share on other sites

If the file only contains just a number use file_get_contents.

 

$number = trim(file_get_contents('c.txt'));

echo 'NUMBER: ' . $number;

 

dont i have to put something to update the number and write it back to the file, so next time someone comes it will +?

Link to comment
Share on other sites

Yes use file_put_contents

 

$number = trim(file_get_contents('c.txt'));

echo 'NUMBER: ' . $number;

$new_number = $number + 6; // whatever you want to add to the number

file_put_contents('c.txt', $new_number);

 

Perfect that worked!

 

Question, is this a good way to track hits? or should i do it in a DB?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.