View Single Post
Old 05-18-2005, 03:21 PM   #6 (permalink)
DJMaze
Senior Contributor
 
DJMaze's Avatar
 
Join Date: Mar 2005
Posts: 672
DJMaze is on a distinguished road
Depends.
We need some server details like:
- speed
- traffic
- bots

All of the above scripts don't use file locking.
File locking is essential when you read/write fast from a file within a milliseconds.

For example you have 4 visitiors with your old script:
#1 opens counter.txt at 0.010 seconds
#2 opens counter.txt at 0.011 seconds
#3 opens counter.txt at 0.012 seconds
#1 writes to file at 0.012 seconds
#2 writes the file data at 0.013 seconds
#3 writes the file data at 0.013 seconds

the entry of #1 is lost cos #2 was to late
#2 and #3 try to write the file at the same time.
This crashes so the file is empty.
Now #4 opens the file at 0.015 seconds and sees he's the first visitor.

To prevent this, you could use file locking.
I will give you an example of a custom function i commonly use
PHP Code:
function file_write($filename, &$content$mode='wb') {
    if (!
$fp fopen($filename$mode)) {
        
trigger_error("Cannot open file ($filename)"E_USER_WARNING);
        return 
false;
    }
    
flock($fpLOCK_EX); // lock it
    
if (fwrite($fp$content) === FALSE) {
        
flock($fpLOCK_UN); // don't forget to unlock
        
trigger_error("Cannot write to file ($filename)"E_USER_WARNING);
        return 
false;
    }
    
flock($fpLOCK_UN); // don't forget to unlock
    
if (!fclose($fp)) {
        
trigger_error("Cannot close file ($filename)"E_USER_WARNING);
        return 
false;
    }
    return 
true;

This way you could use:
PHP Code:
$fstring = "<?phpn$hits $hits;n$file = array(n'".implode("',n'", $file)."'n);";
if (file_write($filename, $fstring)) {
    echo 'cool it worked';
}
else
{
    echo 'something screwey happend, better go look at the shown warnings';
}
databases work differently
they queue the queries into a waitingroom untill it's their turn.
The benefit is that it never goes wrong.
The disadvantage is when your site is heavily visited. Then the queue gets rather full and the script has to wait seconds before it's his turn (10 to 45 seconds is possible)

A similar function is also available in PHP, but we don't gonna use that unless you're a skilled programmer who understands the drawbacks of sleep/wait commands.

It's better to miss a count then to crash a whole server
DJMaze is offline   Reply With Quote