PHP rewrite an included file - is this a valid script?
I've made this question: PHP mutual exclusion (mutex)
As said there, I want several sources to send their stats once in a while, and these stats will be showed at the website's main page.
My problem is that I want this to be done in an atomic manner, so no update of the stats will overlap another one running in the background.Now, I came up with this solution and I want you PHP experts to judge it.
stats.php
<?php
define("my_counter", 12);
?>
index.php
<?php
include "stats.php";
echo constant("my_counter");
?>
upd开发者_开发百科ate.php
<?php
$old_error_reporting = error_reporting(0);
include "stats.php";
define("my_stats_template",'
<?php
define("my_counter", %d);
?>
');
$fd = fopen("stats.php", "w+");
if($fd)
{
if (flock($fd, LOCK_EX))
{
$my_counter = 0;
try
{
$my_counter = constant("my_counter");
}
catch(Exception $e) { }
$my_counter++;
$new_stats = sprintf(constant("my_stats_template"), $my_counter);
echo "Counter should stand at $my_counter";
fwrite($fd, $new_stats);
}
flock($fd, LOCK_UN);
fclose($fd);
}
error_reporting($old_error_reporting);
?>
Several clients will call the "update.php" file once every 60sec each. The "index.php" is going to use the "stats.php" file all the time as you can see.
What's your opinion?
You may find a solution like Memcache may be more intuitive, faster, and useful than rewriting a PHP file every time you want to update the value.
Then there's the idea of stroing it in a database, yes I know this is slow but it's persistent.
Last, rather than writing PHP to a file why not write the value itself to a shared file and just read it? This will work nicely with your locking mechanism and won't require writing 'valid' PHP to a file which just strikes me as wrong.
精彩评论