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).
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>
PHP provides a set of functions to work with MySQL databases. As of the more…
Below is a PHP script that demonstrates how to implement pagination when displaying records from…
Below is a simple PHP script that demonstrates how to search a MySQL database table…
Transferring a WordPress site to a new domain involves several detailed steps to ensure that…
Creating client-server programs in C++ helps in understanding network programming and communication between applications over…
Creating a bookmark system for WordPress can range from simple solutions to more complex ones.…