I am trying to create a cache file from a menu that takes random data called 'includes/menu.php' the random data is created when I run that file manually, it works. Now I want to cache this data into a file for a certain amount of time and then recache it. I am running into 2 problems, from my code cache is created, but it caches the full php page, it does not cache the result, only the code without executing it. What am I doing wrong ? Here is what I have until now :
<?php
$cache_file = 'cachemenu/content.cache';
if(file_exists($cache_file)) {
if(time() - filemtime($cache_file) > 86400) {
// too old , re-fetch
$cache = file_get_contents('includes/menu.php');
file_put_contents($cache_file, $cache);
} else {
// cache is still fresh
}
} else {
// no cache, create one
$cache = file_get_contents('includes/menu.php');
file_put_contents($cache_file, $cache);
}
?>
This line
file_get_contents('includes/menu.php');
will just read the php file, without executing it. Use this code instead (which will execute the php file and save the result into a variable):
ob_start();
include 'includes/menu.php';
$buffer = ob_get_clean();
And then, just save the retrieved content ($buffer) into file
file_put_contents($cache_file, $buffer);
file_get_contents() gets the contents of a file, it doesn't execute it in any way. include() will execute the PHP, but you have to use an output buffer to grab its output.
ob_start();
include('includes/menu.php');
$cache = ob_get_flush();
file_put_contents($cache_file, $cache);
Related
I have a php file that has data coming from the database called Casino-review.php
I just want to copy the php generated output data from this file to a new html file. I have tried lots of other thinks like OB functions, File contents functions, Copy functions, Fopen functions but, nothing work for me. Everthing is working properly creating file copying content but it's showing php code in it. Please help me.
here is the Output.
here is my code
$fileName = $title.".html";
$to = "casinos/all/".$fileName;
$from = "casinos/casino-review.php";
$newcontent = file_get_contents("$from");
if ($createFile = fopen($to, "w+")) {
fread($createFile, filesize($from));
fwrite($createFile, $newcontent);
fclose($createFile);
// echo "Wait for 5 seconds";
// setcookie("file", json_encode($casinoDetails), time() + 7400);
// header("REFRESH: 5;profile/$username/profile.php");
// echo "good";
}
I have finally found my answer
ob_start();
include("$from");
file_put_contents($to, ob_get_contents());
ob_end_clean();
Thanks #Innovin
I try to make my PHP cache with this code:
//Make cache files
$cache = 'tweets-cache.txt';
$date = 'tweets-date.txt';
$currentTime = time(); // Current time
// Get cache time
$datefile = fopen($date, 'r');
$cacheDate = fgets($datefile);
fclose($datefile);
//check if cache has expired
if (floor(abs(($currentTime-$cacheDate) / 10800)) <= $_GET['expiry'] && $cacheDate) {
$cachefile = fopen($cache, 'r');
$data = fgets($cachefile);
fclose($cachefile);
} else {
//Make the REST call
$data = (array) $cb->$api($params);
// update cache file
$cachefile = fopen($cache, 'wb');
fwrite($cachefile, utf8_encode($data));
fclose($cachefile);
// update date file
$datefile = fopen($date, 'wb');
fwrite($datefile, utf8_encode(time()));
fclose($datefile);
}
//Output result in JSON, getting it ready for jQuery to process
echo json_encode($data);
Now he writes nothing in tweets-cache.txt.
i think it is because of he cannot write an array with utf8_encode.
Yes, you are right about utf8_encode() function. Try to write serialized data to the file:
fwrite($cachefile, json_encode($data));
and when you read your data back from the file, do de-serialization:
$data = json_decode(fgets($cachefile));
Also, you can make things simpler if you use functions like file_get/put_contents, so your code:
$cachefile = fopen($cache, 'r');
$data = fgets($cachefile);
fclose($cachefile);
will be:
$data = json_decode(file_get_contents($cache));
and:
// update cache file
$cachefile = fopen($cache, 'wb');
fwrite($cachefile, utf8_encode($data));
fclose($cachefile);
// update date file
$datefile = fopen($date, 'wb');
fwrite($datefile, utf8_encode(time()));
fclose($datefile);
translates to:
// update cache file
file_put_contents($cache, json_encode($data));
// update date file
file_put_contents($date, time());
Be aware of the synchronization problems you can face when you are using filesystem in multithreaded/multiprocess environment.
Two and more php instances can make attempt to write data to the same file in the same time, and you will get corrupted file.
You can use filesystem locking or special cache software like Memcached, which is much more preferable solution for such cases.
Memcached
PHP Reference: file_put_contents()
PHP Reference: file_get_contents()
PHP Reference: json_encode()
I have the following code in a PHP page. Some times when I delete the cache2.html file, I expect the php to recreate it and the next person will get the cache2.html instead of executing the php code. I get the following warning some times on the page and no content. Is it because of multiple users accessing the php concurrently? If so, How do I fix it? Thank you.
Warning: include(dir1/cache2.html) [function.include]: failed to
open stream: No such file or directory in
/home/content/54/site/index.php on line 8
<?php
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
$cachefile = "dir1/cache2.html";
if (file_exists($cachefile)) {
include($cachefile); // output the contents of the cache file
} else {
/* HTML (BUILT USING PHP/MYSQL) */
$cachefile = "dir1/cache2.html";
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_flush(); // Send the output to the browser
}
?>
Calls to file_exists() are themselves cached, so it's likely you're getting a return value of true even after the file is deleted. See:
http://us.php.net/manual/en/function.clearstatcache.php
So, you could do:
clearstatcache();
if (file_exists($cache)) {
include($cache);
} else {
// generate page
}
Alternatively, you could do something like this:
if (file_exists($cache) && #include($cache)) {
exit;
} else {
// generate page
}
Or better, if you're deleting the cache file from within a PHP process, then just call clearstatcache() after you delete the file.
i have read a bit around in the internet about the php cache.
at the moment i am using, this system to cache my pages:
This is putted on the start of the page
<?php
// Settings
$cachedir = 'cache/'; // Directory to cache files in (keep outside web root)
$cachetime = 600; // Seconds to cache files for
$cacheext = 'html'; // Extension to give cached files (usually cache, htm, txt)
// Ignore List
$ignore_list = array(
'addedbytes.com/rss.php',
'addedbytes.com/search/'
);
// Script
$page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page
$cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create
$ignore_page = false;
for ($i = 0; $i < count($ignore_list); $i++) {
$ignore_page = (strpos($page, $ignore_list[$i]) !== false) ? true : $ignore_page;
}
$cachefile_created = ((#file_exists($cachefile)) and ($ignore_page === false)) ? #filemtime($cachefile) : 0;
#clearstatcache();
// Show file from cache if still valid
if (time() - $cachetime < $cachefile_created) {
//ob_start('ob_gzhandler');
#readfile($cachefile);
//ob_end_flush();
exit();
}
// If we're still here, we need to generate a cache file
ob_start();
?>
MY HTML CODE Goes here .............
and the code below is at the footer of my page.
<?php
// Now the script has run, generate a new cache file
$fp = #fopen($cachefile, 'w');
// save the contents of output buffer to the file
#fwrite($fp, ob_get_contents());
#fclose($fp);
ob_end_flush();
?>
There are some things that i need and this code dont have them :
gzip
the expired cache is not autodeleted after it expire.
Also wanted to ask, if this code is secure to use , if some one can suggest a better one or something to improve the current code it will be just great
Thank you fro reading this post.
Best Regards
Meo
….
// Show file from cache if still valid
if (time() - $cachetime < $cachefile_created) {
//ob_start('ob_gzhandler');
echo gzuncompress(file_get_contents($cachefile));
//ob_end_flush();
exit();
} else {
if(file_exists($cachefile) && is_writable($cachefile)) unlink($cachefile)
}
….
and
// Now the script has run, generate a new cache file
$fp = #fopen($cachefile, 'w');
// save the contents of output buffer to the file
#fwrite($fp, gzcompress(ob_get_contents(), 9));
#fclose($fp);
ob_end_flush();
?>
Use ob_start("ob_gzhandler"); to initiate gzipped buffering (it'll take care of determining if the client can actually accept/wants gzipped data and adjust things accordingly).
To delete the cached files:
if (time() - $cachetime < $cachefile_created) {
#readfile($cachefile);
//ob_end_flush();
exit();
} else {
unlink($cachefile);
exit();
}
But there can be delay or maybe error when the file is being written and someone requests for that page. You should use flock to overcome such problems as mentioned at Error during file write in simple PHP caching
Something like this at the end of page
<?php
$fp = #fopen($cachefile, 'w');
if (flock($fp, LOCK_EX | LOCK_NB)) {
fwrite($fp, gzcompress(ob_get_contents(), 9));
flock($fp, LOCK_UN);
fclose($fp);
}
ob_end_flush(); ?>
I am having trouble with an update script. It runs for a few hours so I would like it to output live to a text file.
I start the document with
ob_start();
Then within the while loop (as it iterates through the records of the database) I have this
$size=ob_get_length();
if ($size > 0)
{
$content = ob_get_contents();
logit($contents);
ob_clean();
}
And finally the logit function
function logit($data)
{
file_put_contents('log.txt', $data, FILE_APPEND);
}
However the log file remains empty. What am I doing wrong?
try
logit($content);
// ^^ Note the missing s
$contents is not the same variable as $content.
For anyone coming here looking for a function for this, I wrote a nice one today:
//buffer php outout between consecutive calls and optionally store it to a file:
function buffer( $toFilePath=0, $appendToFile=0 ){
$status = ob_get_status ();
if($status['level']===1) return ob_start(); //start the buffer
$res = ob_get_contents();
ob_end_clean();
if($toFilePath) file_put_contents($toFilePath, $res, ($appendToFile ? FILE_APPEND : null));
return $res;
}
Sample usage:
buffer(); //start the buffer
echo(12345); //log some stuff
echo(678910);
$log = buffer('mylog.txt',1); //add these lines to a file (optional)
echo('Heres the latest log:'.$log);