I’m using AWS, Ubuntu – LAMP for running my PHP application. I implemented a cache code and was all working fine on localhost, but did not work on server
Below is my folder structure
/app
- /cache_files
- index.php
- contact.php
in .htaccess I’ve set root folder as /app so all the requested are executed from /app folder itself.
Below I’m using the structure
<?php include("cache_header.php"); ?>
<html>
<body>
Body Contents
</body>
</html>
<?php include("cache_footer.php"); ?>
Code for cache_header.php
<?php
$url = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $url);
$file = $break[count($break) - 1];
$cachefile = 'cache_files/cached-'.substr_replace($file ,"",-4).'.html';
$cachetime = 18000;
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile))
{
// echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
readfile($cachefile);
exit;
}
ob_start(); // Start the output buffer
?>
Code for cache_footer.php
<?php
// Cache the contents to a cache file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser
?>
When the above code is executed on localhost it stores the cache file in cache_files/
directory but when i run the same code online it does not save the generated cache file in cache_files/
directory.
If i use below code it generates the cache file and store inside the /app directory where the index file is
$cachefile = 'cached-'.substr_replace($file ,"",-4).'.html';
but if i put cache_files/
it does not work. Why is it so? Where am i going wrong?
When i viewed the apache logs online, it showed me below errors.
fwrite() expects parameter 1 to be resource, boolean given
fclose() expects parameter 1 to be resource, boolean given
open(/cache_files/cached-contact.html): failed to open stream: No such file or directory