Simplify my PHP code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Noah
Forum Newbie
Posts: 7
Joined: Sat Jun 19, 2004 3:34 pm

Simplify my PHP code

Post by Noah »

I created a web counter to count a user only once per session. I think I may have done things the long way, lol. Tell me what you think.

Code: Select all

<?php

   session_start();

   if (!session_is_registered("counted")){
      $fp = fopen("count.txt", "r");
      $count = fgets($fp);
      $count = $count + 1;
      fclose($fp);
      $fp = fopen("count.txt", "w");
      fwrite($fp, "$count");
      fclose($fp);
      session_register("counted");
   }

$fp = fopen("count.txt", "r");
$count = fgets($fp);
print "$count";

?>
[edit=Weirdan] use

Code: Select all

tags to make your code readable [/edit] [/color]
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Code: Select all

session_start();
 $fp = fopen('count.txt', 'r+');
 $count = fgets($fp);
 if ( !session_is_registered('counted') ) {
    fseek($fp, 0, SEEK_SET);
    fwrite($fp, ++$count);
    session_register('counted');
 }
 fclose($fp);
 echo $count;
User avatar
Noah
Forum Newbie
Posts: 7
Joined: Sat Jun 19, 2004 3:34 pm

Post by Noah »

Thanks. You can tell I'm new at this, haha.
Post Reply