Uhhh, exactly how many times do you want to open the file, close the file, and fork another process just to update this counter? Try this for lower overhead (caution-- not tested!):
function counthits($file)
{
if (! ($fd = fopen($file,"a+")))
{
$ctr = 0;
}
else
{
fseek( $fd, 0 ); // back to beginning of file for read
if ($ctr = fgets($fd, 32))
{
$ctr++;
}
else
{
$ctr = 0;
}
fseek( $fd, 0 ); // back to beginning again for write
fputs( $fd, "$ctr\n" );
fclose($fd);
}
return $ctr;
Note that append-update mode is the only one that gives you everything you need in a single call to fopen():
* creates the file if it doesn't already exist
* retains the existing contents if it does
* allows both reading and writing
if (! $fd)
// append-update mode is the only correct one:
// creates the file if it does