Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 Answer

You append the text file, that is why this is happening.

My advice is to use file_get_contents and file_put_contents.

$i = file_get_contents("invoices/invoice1/backupN.txt");
$i++;
Echo $i;
file_put_contents("invoices/invoice1/backupN.txt" $i);

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.

file_put_contents("invoices/invoice1/backupN.txt", file_get_contents("invoices/invoice1/backupN.txt")+1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...