PHP缓存无法处理包含的文件

时间:2013-01-03 15:32:20

标签: php web-services caching buffer

我有一个网页表单,其中包含一个包含文件,可以输出状态选项。 html看起来像

    <select name="state" id="state">
        <option value="">--</option>
        <?php include ("resources/data/stateoptions.php"); ?>
      </select>

状态选项调用Web服务,以便商店位置列表始终是最新的。然而,似乎这个联系表单页面运行异常缓慢(如果我删除此包括更快)。所以我想缓存Web服务调用。我的州选项文件如下所示

<?php
  $cachefile = "cache/states.html";
  $cachetime = 5 * 60; // 5 minutes

  // Serve from the cache if it is younger than $cachetime
  if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) 
  {
     include($cachefile);

     echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." 
     -->n";

     exit;
  }

  ob_start(); // start the output buffer
?>

<?php
//url of locations web service
$serviceURL = 'http://webserviceurl/state';

//query the webservice
$string = file_get_contents($serviceURL);

//decode the json response into an array
$json_a=json_decode($string,true);

foreach( $json_a as $State => $IdealState){
$IdealState = $IdealState[State];
$IdealState2 = str_replace(' ', '-', $IdealState);
echo '<option value='.$IdealState2.'>'.$IdealState.'</option>';
}
?>

<?php
// open/create cache file and write data
$fp = fopen($cachefile, 'w'); 
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents()); 
// close the file
fclose($fp); 
// Send the output to the browser
ob_end_flush(); 
?>

当我直接调用此文件时,一切都按预期工作,并创建了states.html文件。出于某种原因,当stateoptions.php文件包含在我的联系表单页面中时,它永远不会创建缓存文件,并且速度问题仍然存在。我是一个相当新手的程序员,所以任何帮助都会非常感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

这里的问题很可能是相对路径和工作目录。包含的文件从调用脚本继承其工作目录,它获取它自动驻留的位置的工作目录。

您需要使用类似魔术__DIR__常量的东西来构建绝对路径,或相应地调整相对路径。

我会在这里稍微说一下,如果你把第一行更改为:

$cachefile = "resources/data/cache/states.html";

...你可能会发现它适用于你期望它。