I am working on a site that is built on LAMP, which pulls data(car dealership inventories) from an XML feed and displays it on the site. There is a rotator on the index page which displays 4 random cars, however there is a long delay on page load – about 7-10 seconds. This is because the site is cycling through the data to find cars that have images and meet other criteria before displaying the results. My developer put together this script to cache the results for 5 minutes:
/*
* Cache requests for 5 minutes
* Wraps original method (now _sendRequest)
*/
private function sendRequest($xml) {
error_log($xml);
$cache_filename = dirname(__FILE__) . '/cache/' . md5($xml);
if (file_exists($cache_filename) && (time() - filemtime($cache_filename)) < 300 && filesize($cache_filename) > 100) {
return file_get_contents($cache_filename);
} elseif (file_exists($cache_filename)) {
unlink($cache_filename);
}
$response = $this->_sendRequest($xml);
if (!is_dir(dirname($cache_filename))) {
@mkdir(dirname($cache_filename),0775,true);
}
@file_put_contents($cache_filename, $response);
return $response;
}
private function _sendRequest($xml) {
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_POST => true,
CURLOPT_USERAGENT => Config::$appName,
CURLOPT_USERPWD => Config::$aweAPIKey,
CURLOPT_URL => Config::$aweAPIURL,
CURLOPT_POSTFIELDS => $xml
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
//echo "ERROR: " . curl_error($ch);
curl_close($ch);
return $content;
}
The directory of the script is in /lib/client.php and it is saving large amounts of text files containing vehicle data in /lib/cache, however the site page load is not decreasing. Are there some changes I should make to the script or how it is saving the cached data?
Hitting the hard disk with every request is expensive in terms of performance, so logically your cache system there isn’t really gonna help. Instead look into APC, memcached or Redis as they allow you to store data directly in memory, which is much faster to read and write.