PHP将计数器增加1并保存在txt文件中

时间:2017-12-22 16:35:37

标签: php

我正在尝试使用我的php脚本从“counter.txt”文件中读取当前计数并添加1并将其保存回计数器文本文件中。

$filename = 'counter.txt';

// create the file if it doesn't exist
if (!file_exists($filename)) {
    $counter_file = fopen($filename, "w");
    fwrite($counter_file, "0");
    $counter = 0;
} else {
    $counter_file = fopen($filename, "r");

    // will read the first line
    $counter = fgets($counter_file);
}

// increase $counter
$counter++;

// echo counter
echo $counter;

// save the increased counter
fwrite($counter_file, "0");

// close the file
fclose($counter_file);

脚本读取并回显数字,但不会保存带有增加数字的文件。

请帮忙

3 个答案:

答案 0 :(得分:4)

如果这只是一个熟悉各种文件功能的学习练习,这可能没有用,但使用file_get_contentsfile_put_contents可能会更简单。

$file = 'counter.txt';

// default the counter value to 1
$counter = 1;

// add the previous counter value if the file exists    
if (file_exists($file)) {
    $counter += file_get_contents($file);
}

// write the new counter value to the file
file_put_contents($file, $counter);

当然,无论这种方式是否有效,或者您尝试这样做的方式完全取决于文件是否可写,因此您还需要确定权限设置正确。

答案 1 :(得分:0)

为我工作:

$counter = 1;
$file_name = 'test.'.$counter.'.ext';
if (file_exists($file_name)) {
    $counter++;
    fopen('test'.$counter.'.ext' , "w");
}
else {
    fopen('test'.$counter.'.ext' , "w");
}

答案 2 :(得分:-1)

<?php

$filename = 'counter.txt';

// create the file if it doesn't exist
if (!file_exists($filename)) {
    $counter_file = fopen($filename, "w");
    fwrite($counter_file, "1");
    fclose($counter_file);
} else {
    $counter_file = fopen($filename, "w+");
    $fsize = filesize($filename);
    // will read the whole file
    $counter = (int) fread($counter_file, $fsize);
    $counter++;

    fwrite($counter_file, $counter);
    fclose($counter_file);
}