PDA

View Full Version : Won't re-write file (Im new at this)


Riboflavin
01-12-2005, 12:35 AM
I just started looking into PHP today but anyways here the short code im trying to write for basically a hit counter.

This is uploaded in a file called count.php
<?php

$name = file("hits.txt");
$add ++;
$write = fopen("hits.txt", "w");
fputs($write , "$add");
fclose($write);
readfile("hits.txt");

?>

Then I uploaded a file called hits.txt with just "0" written in it.

In the index file I have include(count.php)

The first time it loads it displays nothing the second time it displays a '1' then it just keeps at '1' no matter how many times it loads.


Thanks for any help

mattw
01-12-2005, 01:09 AM
did u chmod both files to 777?

Riboflavin
01-12-2005, 01:12 AM
I did for the txt file should I do the count.php too?


EDIT: I tried going to 777 for all no help

Riboflavin
01-12-2005, 01:37 AM
Ok my code was just way off I had some vars that I didn't need etc.

Aarron sharred this with me on AIM
<?
$count = (int) file_get_contents ('counter.txt');
$count++;
$file_pointer = fopen ('counter.txt', 'w');
fwrite ($file_pointer, $count);
fclose ($file_pointer);

// $count holds the same value as your hit counter, so you can just echo $count
echo 'There have been '.$count.' visitors to this page.';
?>

AaronW
01-12-2005, 01:38 AM
Solved over IM, but will post the answer here:

The problem was that a) $add wasn't defined (you meant to use $name) and that b) file () returns an array with each value being a line of the file. You want file_get_contents ().


<?
$count = file_get_contents ('counter.txt');
$count++;
$file_pointer = fopen ('counter.txt', 'w');
fwrite ($file_pointer, $count);
fclose ($file_pointer);

// $count holds the same value as your hit counter, so you can just echo $count
echo 'There have been '.$count.' visitors to this page.';
?>