
Below is a simple caching script using PHP and JavaScript. This script caches the results of an API call on the server side (PHP) and retrieves it on the client side (JavaScript).
PHP Caching Script (cache.php
)
<?php // Set the cache file path $cacheFile = 'cache/data_cache.json'; // Set cache lifetime (in seconds) $cacheLifetime = 300; // Cache for 5 minutes // Check if the cache file exists and is not expired if (file_exists($cacheFile) && (filemtime($cacheFile) > (time() - $cacheLifetime))) { // Cache is valid, read the data from the cache $data = file_get_contents($cacheFile); } else { // Cache is expired or does not exist, fetch fresh data // This is where you would typically fetch data from an API or database $data = fetchFreshData(); // Assume this function fetches your data // Save the fresh data to the cache file file_put_contents($cacheFile, $data); } // Set the content type to JSON header('Content-Type: application/json'); echo $data; // Function to fetch fresh data (mockup) function fetchFreshData() { $freshData = [ 'message' => 'This is fresh data!', 'timestamp' => time() ]; return json_encode($freshData); } ?>
JavaScript to Retrieve Cached Data (script.js
)
// Fetch the cached or fresh data from the PHP script fetch('cache.php') .then(response => { // Check if the response is ok (status 200) if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); // Parse the JSON data }) .then(data => { // Process the received data console.log('Received Data:', data); document.getElementById('output').innerText = data.message + ' (Fetched at: ' + new Date(data.timestamp * 1000).toLocaleTimeString() + ')'; }) .catch(error => { console.error('There was a problem with the fetch operation:', error); });
HTML Example to Use the JavaScript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Caching Example</title> <script src="script.js" defer></script> </head> <body> <h1>Cache Example</h1> <div id="output">Loading...</div> </body> </html>
Explanation
- Caching Logic in PHP:
- The PHP script checks if the cache file exists and whether it is still valid based on the set cache lifetime.
- If the cache is valid, it reads the data from the cache file. If it’s expired or doesn’t exist, it fetches fresh data (you can modify this part to fetch from a real API or database) and then saves it to the cache file for future use.
- JavaScript Fetch:
- The JavaScript code makes a fetch request to the PHP script to retrieve the cached data.
- It processes the response and updates the HTML content dynamically based on the data received.
- HTML Structure:
- A simple HTML structure is provided to display the retrieved data on the web page.