簡體   English   中英

PHP緩存不適用於包含的文件

[英]PHP Caching not working on Included File

我有一個包含包含文件的Web表單,該文件輸出狀態的選擇選項。 的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文件包含在我的聯系表單頁面中時,它永遠不會創建緩存文件,並且速度問題仍然存在。 我是一個相當新手的程序員,所以我們將不勝感激。

謝謝!

這里的問題很可能是相對路徑和工作目錄。 所包含的文件從調用腳本繼承其工作目錄,它不會在它自動所在位置的工作目錄。

您要么需要使用諸如魔術__DIR__常量之類的東西來構造絕對路徑,要么相應地調整相對路徑。

我將在這里稍作停留,然后說,如果您將第一行更改為:

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

...您可能會發現它可以按您期望的那樣工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM