php横幅缓存建议

时间:2012-08-20 11:10:46

标签: php caching banner

我们为几个高负载站点提供服务,到目前为止,我们提供了此代码,用于缓存支持一些基本本地标题轮换的远程横幅。所有人都应该很容易理解,我希望听到您对此代码的可能改进或建议。 这是......

        $cachetime = 6 * 60 * 60; // 6 hours
        $bannercache = $_SERVER['DOCUMENT_ROOT']."/banner-".$bpos.".txt";

            // Serve from the cache if it is younger than $cachetime

            if (file_exists($bannercache) && (time() - $cachetime
             < filemtime($bannercache)))
            {

                    // if it's ok don't update from remote

            } else {

                    // if cache is old, update from remote


                    $bannercachecontent = @file_get_contents('ADSERVER.com/showad.php?category='.$adcat.'&dimensions='.$dimensions);

                    if ($bannercachecontent === FALSE) {

                        // on error, just update local time, so that it's not pulled again in case of remote mysql overload

                        $fb = @fopen($bannercache, 'a+');
                        fwrite($fb, "\n<!-- Changed date on ".date('jS F Y H:i', filemtime($cachefile))."-->\n");
                        fclose($fb);

                    } else {

                        // if it's ok, save new local file

                        $fb = @fopen($bannercache, 'w');
                        fwrite($fb, $bannercachecontent);
                        fwrite($fb, "\n<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))."-->\n");
                        fclose($fb);
                    }



            }



        $fhm = file_get_contents($bannercache);



        $fhmpos = strpos($fhm, '-----#####-----'); // check if it needs to be exploded for rotation
        if ($fhmpos === false) {

            echo $fhm;

        } else {

            $fhmpicks = explode("-----#####-----", $fhm);


        foreach ($fhmpicks as $fhmkey => $fhmvalue)
        {
            if (trim($fhmpicks[$fhmkey]) == '')
            {
                unset($fhmpicks[$fhmkey]);
            }
        }


            $fhmpick = array_rand($fhmpicks,1);

            echo $fhmpicks[$fhmpick]; // show only one banner

        }

1 个答案:

答案 0 :(得分:0)

不要让您的客户更新您的横幅广告。您将始终有1个用户必须执行此操作,并且没有必要:

相反:让客户端始终加载本地图像,并运行后台进程(cron,如果您想立即拉动图像,则使用手动覆盖)获取正确的图像

代码非常简单:

您的客户:$yourImage= $_SERVER['DOCUMENT_ROOT']."/banner-".$bpos.".txt";

并且您的更新脚本只能cURL正确的图像。