0

I have small code.

total_request.txt is text file have content value =1

$file = 'total_request.txt';
$count = file_get_contents( $file );
echo $a = $count + 1;  
file_put_contents( $file, $a ); 

code output value: 2

but file total_request.txt have content 3. I want to automatically increment 1 when running this file php.

what is wrong in my code?

Barmar
  • 741,623
  • 53
  • 500
  • 612
cudan706
  • 1
  • 1
  • What do you mean? If the file doesn't exist, it will be created, with value 1. If not, it will be increased by 1, and the output will match the content of the file... what exactly do you think is wrong? – junkfoodjunkie Mar 27 '17 at 21:30
  • 2
    @junkfoodjunkie He's saying that the file goes from 1 to 3 instead of from 1 to 2. I can't reproduce this problem. – Barmar Mar 27 '17 at 21:32
  • Is this code inside a function or something and is getting executed twice? Is there any way for you to tell? Could you possibly try appending the contents temporarily instead of overwriting them - [`FILE_APPEND`](http://php.net/manual/en/function.file-put-contents.php)? – Dhruv Saxena Mar 27 '17 at 21:47
  • Aha. No, can't reproduce either. It works as it should. – junkfoodjunkie Mar 27 '17 at 22:21

1 Answers1

0

You're probably looking to open a file in append mode:

<?php
$fp = fopen('data.txt', 'a');//opens file in append mode  
fwrite($fp, ' this is additional text ');  
fwrite($fp, 'appending data');  
fclose($fp);
?>

I hope it may help you.

Regards.