PHP rewrite an included file - is this a valid script?

寵の児 提交于 2019-12-07 19:21:31

问题


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");
?>

update.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?


回答1:


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.



来源:https://stackoverflow.com/questions/2922959/php-rewrite-an-included-file-is-this-a-valid-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!