note 48408 added to function.fwrite

From: Date: Wed, 22 Dec 2004 17:56:08 +0000
Subject: note 48408 added to function.fwrite
Groups: php.notes 
Request: Send a blank email to php-notes+get-82181@lists.php.net to get a copy of this message
Watch out for mistakes in writting a simple code for a hit counter: <?php $cont=fopen('cont.txt','r'); $incr=fgets($cont); //echo $incr; $incr++; fclose($cont); $cont=fopen('cont.txt','a'); fwrite($cont,$incr); fclose($cont); ?> Why? notice the second fopen -> $cont=fopen('cont.txt','a'); it opens the file in writting mode (a). And when it ads the incremented value ( $incr ) it ads it ALONG the old value... so opening the counter page about 5 times will make your hits number look like this 012131214121312151.21312141213E+ .... you get the piont. nasty, isn't it? REMEMBER to open the file with the 'w' mode (truncate the file to 0). Doing this will clear the file content and it will make sure that your counter works nice. This is the final code <?php $cont=fopen('cont.txt','r'); $incr=fgets($cont); //echo $incr; $incr++; fclose($cont); $cont=fopen('cont.txt','w'); fwrite($cont,$incr); fclose($cont); ?> Notice that this work fine =) XU (alias Iscu Andrei) ---- Manual Page -- http://www.php.net/manual/en/function.fwrite.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+48408 Delete -- http://master.php.net/manage/user-notes.php?action=delete+48408&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48408&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48408&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48408&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48408&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48408&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+48408&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#82181) next »