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>
WordPress development has evolved significantly, and modern tooling plays a crucial role in creating efficient…
I. Project Overview The goal is to automate the process of notifying search engines (like…
1. Database Structure (MySQL) We'll need a database table to store information about our website's…
This explanation aims to provide a solid foundation for understanding the process and implementing your…
Okay, here's a comprehensive guide on building a real-time website chat script using PHP, HTML,…
Comprehensive guide on creating a simple website analytics system using PHP, HTML, CSS, JavaScript, and…