I want to be able to +1 to $i
every page reload.
I have come across a very simple issue, that I am struggling to find a solution online.
Heres my code:
$backupNumber = fopen("$v", "r+") or die("Unable to open file!");
$i = fread($backupNumber,filesize("invoices/invoice1/backupN.txt"));
$i = intval($i);
$i = $i + 1;
echo $i;
fwrite($backupNumber,$i);
$a = "invoices/" . $invoiceN . "/backup" . $i;
fclose($backupNumber);
and in the txt file is simply the number '1' to start off with.
The issue occurs when reloading the page when I echo $i it outputs:
2 then 13 then 1214 then 12131215 then 2147483648 etc.
I want it to simple output
2 then 3 then 4 etc
Another variation on a theme perhaps...
You are appending the file thats why this is happening. Instead of using r+ mode just use w+ mode. r+ mode only opens a file and allow you to read and write but dont over write the content. Where as in w+ mode always a new empty file is created.
Do something like
Else you can also you fseek() to point at 0th location in file and override the content in file.
You append the text file, that is why this is happening.
My advice is to use file_get_contents and file_put_contents.
File get and put contents always reads the whole text file.
I don't think you need to intcast the string, it should work without it.
The code can be a one liner too. It's messy but compact.
After reading the number from the file, the handle is positioned at its end, so while your math is sound, you're appending the new number to the file instead of overwriting it.
One approach to handle this is to reset the handle use
fseek
before writing: