What exactly do you mean it "doesn't work or will return with an internal server error"? You haven't really said what your problem is. What is the error message? On which step does it fail -- creating the countlog.txt file and writing "New" if it doesn't exist? Giving the "Cannot read file" error on fopen(), or something after that?
I can take a few guesses:
- Echo $path to see what file path it's actually trying to use. Does the PathTo folder exist? Do you have permissions to write to files in it? File_put_contents creates a filename that doesn't exist, but not a directory. You need to create the folder -- manually, or using mkdir() in your code (file_exists() or is_dir() can check whether the folder exists).
- If the script creates your file and writes "New" in it, $count doesn't contain a number in the next step, which doesn't make much sense. Although intval() of an alphabetical string will usually return 0, that is unpredictable behavior. Logically, a hit counter should just start with the number 0 (or 1, if not incrementing again for the first hit) and increment from there. You also don't need to take the absolute value of a hit counter that starts at zero and only goes up.
- Add some debugging code if you don't know where the script is failing. I.e, fgets() returns false if there's an error. You could have an if statement that says "Error on fgets" if it's false to narrow the problem down to that line.
- For a web page hit counter, you probably want to output HTML formatting for the results. So echo <br> instead of \n for a line break.
More generally, your code is much longer than it needs to be and has extra file operations. You only need to read the file once, and then write to the file once. Something like this:
<?php
$path = __DIR__ . '\PathTo\countlog.txt';
if(file_exists($path))
{
$count = file_get_contents($path);
}
else
{
$count = 0;
}
$count++;
file_put_contents($path, $count);
echo "$count hit(s)<br>";
?>
There are ways this could be made shorter , such as using the ternary conditional operator instead of the long if-else statement, but this code is easier to understand. File_put_contents will produce a warning (not an error) if the file doesn't exist: you can suppress it with an @ symbol before the function call, or create the file using fopen() inside the else {} block.