Very simple code - doesn't work

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
Eddie1506
Forum Newbie
Posts: 2
Joined: Thu Jun 23, 2005 10:02 am

Very simple code - doesn't work

Post by Eddie1506 »

Code: Select all

<?php
        $not_open = 0;
        if(($counter = fopen("counter.txt", "r")) == NULL)
                $not_open = 1;
        if($not_open == 0)
        {
                fscanf($counter, "%d", $number);
                fclose($counter);
                $number++;
                $not_open = 0;
                if(($counter = fopen("counter.txt", "w")) == NULL)
                        $not_open = 1;
                if($not_open == 0)
                {
                        fprintf($counter, "%d", $number);
                        fclose($counter);
                }
        }
?>
Hello everyone!

Why doesn't this piece of code work? Problem is with fprintf in the end... Second fopen opens the file for writing and deletes it's content, but fprintf doesn't write anything to it... As a result, i get a blank file counter.txt and HTML page, of which this code is part, doesn't show... I only get blank file...

Thanks for any help!
User avatar
senthilnayagam
Forum Newbie
Posts: 17
Joined: Wed Jun 08, 2005 5:36 am
Location: Bangalore

Re: Very simple code - doesn't work

Post by senthilnayagam »

found a small counter which can do uniques too

http://www.radiantfx.com/tutorials/1/15 ... MySQL).php

Code: Select all

<?
if(!session_id()){
    session_start();
}
if($_SESSION['tracked'] == "") {
    $_SESSION['tracked'] = "done";
    $path = $PHP_SELF."/counter/";
    $fp = fopen($path."total.txt", "r");
    $total = fread($fp, 10000) + 1;
    fclose($fp);
    $fp = fopen($path."total.txt", "w");
    fwrite($fp, $total);
    fclose($fp);
}
function output_total() {
    $path = $PHP_SELF."/counter/";
    $fp = fopen($path."total.txt", "r");
    $total = fread($fp, 10000) + 1;
    fclose($fp);
    echo $total;
}
?>
some of the conditions you put were redundant

also always close the file which you open

regards
Senthil
Eddie1506
Forum Newbie
Posts: 2
Joined: Thu Jun 23, 2005 10:02 am

Re: Very simple code - doesn't work

Post by Eddie1506 »

senthilnayagam wrote:found a small counter which can do uniques too
Thanks! I'll use it if I can't figure out what's wrong with mine.
some of the conditions you put were redundant
you mean those with if (($counter = fopen()) == NULL)?

You're probably right, but i'm used to write them.... 6 years developing in C does it's thing, you know! ;)
also always close the file which you open
I did, that's why i don't understand why it doesn't work.
Post Reply