add a string and a number in a sum

2019-08-17 08:36发布

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

标签: php file
4条回答
Lonely孤独者°
2楼-- · 2019-08-17 09:14

Another variation on a theme perhaps...

function updatecount(){
    $file='invoices/invoice1/backupN.txt';
    if( !realpath( $file ) )$i=0;
    $i=intval( trim( file_get_contents( $file ) ) ) + 1;
    file_put_contents( $file, $i );
    return $i;
}

$count=updatecount();
echo strval( $count );
查看更多
狗以群分
3楼-- · 2019-08-17 09:16

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

$backupNumber = fopen("$v", "r+") or die("Unable to open file!");
$i = fread($backupNumber,filesize("invoices/invoice1/backupN.txt"));
fclose($backupNumber);

$backupNumber = fopen("$v", "w+") or die("Unable to open file!");
 $i = intval($i);
 $i = $i + 1;
echo $i;
fwrite($backupNumber,$i);
$a = "invoices/" . $invoiceN . "/backup" . $i; fclose($backupNumber);

Else you can also you fseek() to point at 0th location in file and override the content in file.

查看更多
走好不送
4楼-- · 2019-08-17 09:27

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);
查看更多
看我几分像从前
5楼-- · 2019-08-17 09:34

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:

fseek($backupNumber, 0);
fwrite($backupNumber, $i);
查看更多
登录 后发表回答