PHP

Simple caching script using PHP and JavaScript.

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

  1. 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.
  2. 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.
  3. HTML Structure:
    • A simple HTML structure is provided to display the retrieved data on the web page.
Victoria

Im just a girl who hanging around with her friends ;)

Recent Posts

PHP functions for working with MySQL: a detailed description

PHP provides a set of functions to work with MySQL databases. As of the more…

2 days ago

PHP pagination script from MySQL

Below is a PHP script that demonstrates how to implement pagination when displaying records from…

2 days ago

MySQL database table search script in PHP

Below is a simple PHP script that demonstrates how to search a MySQL database table…

2 days ago

Step-by-Step Guide to Moving Your WordPress Site to a New Domain

Transferring a WordPress site to a new domain involves several detailed steps to ensure that…

4 days ago

5 examples of creating client-server applications in C++

Creating client-server programs in C++ helps in understanding network programming and communication between applications over…

6 days ago

5 bookmark script options for wordpress

Creating a bookmark system for WordPress can range from simple solutions to more complex ones.…

6 days ago