简体   繁体   中英

PHP Caching not working on Included File

I have a web form that has an included file that outputs select options for states. The html looks like

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

The state options makes a call to a web service so that the list of store locations is always current. It seems however that this contact form page runs exceptionally slow (much faster if I remove this include). So I want to cache the web service call. My state options file looks like this

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

When I call this file directly, everything works as expected, and a states.html file is created. For some reason however when the stateoptions.php file is included in my contact form page, it never creates a cache file, and the speed problem persists. I'm a fairly novice programmer, so any help would be much appreciated.

Thanks!

The problem here is most likely going to be relative paths and working directories. The included file inherits its working directory from the calling script, it does not get a working directory of the location in which it resides automatically.

You either need to use the something like the magic __DIR__ constant to construct an absolute path, or adjust the relative path accordingly.

I'm going to go out on a limb a little bit here and say that if you change the first line to:

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

...you will probably find it works at you expect it to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM