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

Building Your Next Project with wp-scripts: A Comprehensive Guide

WordPress development has evolved significantly, and modern tooling plays a crucial role in creating efficient…

1 week ago

Script for automatically informing search engines about new content on website

I. Project Overview The goal is to automate the process of notifying search engines (like…

2 weeks ago

Creating an XML sitemap script with PHP, designed for automated updates via CRON

1. Database Structure (MySQL) We'll need a database table to store information about our website's…

2 weeks ago

Comprehensive guide on building a URL shortening script

This explanation aims to provide a solid foundation for understanding the process and implementing your…

2 weeks ago

Guide on building a real-time website chat script

Okay, here's a comprehensive guide on building a real-time website chat script using PHP, HTML,…

2 weeks ago

Comprehensive guide on creating a simple website analytics system

Comprehensive guide on creating a simple website analytics system using PHP, HTML, CSS, JavaScript, and…

2 weeks ago