user215584
user215584

Reputation: 105

Simple count system. PHP/.TXT file

I have the following simple count, system and I have 2 things, that I can't do. Here is my count.php file:

<?php
if (file_exists('admin/all_count.txt')){
    $fil = fopen('admin/all_count.txt', r);
    $dat = fread($fil, filesize('admin/all_count.txt'));
    echo $dat+1;
    fclose($fil);
    $fil = fopen('admin/all_count.txt', w);
    fwrite($fil, $dat+1);
}
else 
{
    $fil = fopen('admin/all_count.txt', w);
    fwrite($fil, 1);
    echo '1';
    fclose($fil);
}
?>

Here is the content of the all_count.txt file (but I don't think you need it, anyway):

81

Questions:-

  1. So to make count.php work, I place <?php include("count.php"); ?> inside the page which counts I would like to count, BUT where I put this include, it is showing the actual content of all_count.txt file in the webpage, which I would like to be hidden.
  2. I would like to make a script that makes the content of the all_count.txt file to zero. Thank you guys in advance.

I tried this for making it zero a week ago, but didn't work: I tried this for make it zero, and didn't work: zero.php:

<?php
if (file_exists('admin/all_count.txt')){
    $fil = fopen('admin/all_count.txt', r);
    $dat = fread($fil, filesize('admin/all_count.txt'));
    $dat-$dat;
    fclose($fil);
    $fil = fopen('admin/all_count.txt', w);
    fwrite($fil, $dat-$dat);
}
else 
{
    $fil = fopen('admin/all_count.txt', w);
    fwrite($fil, 0);
    echo '0';
    fclose($fil);
}
?>

Upvotes: 1

Views: 306

Answers (2)

Alexey
Alexey

Reputation: 3484

  1. Consider using a database for this. You'll have to deal with concurrency access issues with the file.
  2. You can open your file once for reading and writing
  3. You should enclose 'r' and 'w' access modifiers into the quotes
  4. You should not echo it (if you don't want the output)
  5. in order to zero the content of the file oyu can just do

    file_put_contents('admin/all_count.txt','0');

  6. You can just use file_get_contents/file_put_contents - I think it will be easier for you.

Upvotes: 3

Toon Casteele
Toon Casteele

Reputation: 2579

  1. Don't use echo if you don't want stuff to show up on your page.

  2. you already have a way to write the count to your txt file, why wouldn't you be able to just write 0 to it?

Upvotes: 1

Related Questions