PHP Partial Caching refers to the practice of storing and

I am looking to partially cache some php files. For example:

<?
echo "<h1>", $anyPerdefinedVarible, "</h1>";
echo "time at linux is: ";
// starting not been cached section
echo date();
//end of partial cach
echo "<div>goodbye $footerVar</div>";
?>

So the cached page should look like this (cached.php)

<h1>This section is fixed today</h1>
<? echo date(); ?>
<div>goodbye please visit today's suggested website</div>

Although it can be done with templating, I prefer a direct solution for this. I am seeking an alternative approach.

Answer №1

Take a look at the PHP function ob_start(), which can buffer all output and save it. For more information, visit here.

Additionally, you can refer to this link for the specific function you need. For a simpler version, check out this link.


Here is a simple but effective solution:

In template.php:

<?php
    echo '<p>Now is: <?php echo date("l, j F Y, H:i:s"); ?> and the weather is <strong><?php echo $weather; ?></strong></p>';
    echo "<p>Template is: " . date("l, j F Y, H:i:s") . "</p>";
    sleep(2); // wait for 2 seconds
?>

In actualpage.php:

<?php    
    function get_include_contents($filename) {
        if (is_file($filename)) {
            ob_start();
            include $filename;
            return ob_get_clean();
        }
        return false;
    }

    // Variables
    $weather = "fine";

    // Evaluate the template
    eval("?>" . get_include_contents("template.php"));
?>

You can save the contents of template.php or actualpage.php using file_put_contents() to a file like cached.php. Then you can have actualpage.php check the date of cached.php and either create a new one or reuse the existing one.


Based on comments, here is how you can cache the template:

<?php    
    function get_include_contents($filename) {
        if (is_file($filename)) {
            ob_start();
            include $filename;
            return ob_get_clean();
        }
        return false;
    }

    file_put_contents("cachedir/cache.php", get_include_contents("template.php"));

?>

To run this, you can directly execute the cached file or include it in another page like this:

<?php
    // Variables
    $weather = "fine";

    include("cachedir/cache.php");
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using PHP along with JQuery and AJAX to update the database when a Div element is hidden

My website has a complex setup, so I will simplify it with an example. Current Configuration I currently have two buttons. <a id="one" href="#">Link 1</a> <a id="two" href="#">Link 2</a> Additionally, I have two divs. <div i ...

Uploading images dynamically using Ajax and PHP upon submission

Currently, I am working on a modal that submits information and an image through a form to a database using PHP and JavaScript. However, my expertise in JavaScript is limited, so I could use some assistance. So far, I have successfully inserted data from ...

Troubleshooting a GD library issue: resolving the white screen dilemma

I'm currently facing an issue with the GD PHP library. When I attempt to send an image to a localhost VM, the image displays properly on the screen. However, when trying to do the same on a VPS, the image does not generate and the screen remains white ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

Switch back JSON in php script

After receiving a JSON object with an unspecified number of key/value pairs, I need to send it from my $.ajax function to a PHP script. The PHP script must then revert the JSON object and send it back to jQuery. {"First name": "John", "Contact": "2323",.. ...

What is the best way to create a query that retrieves specific data from multiple tables simultaneously?

In my current project, I have a feeds menu similar to Facebook. I am looking to display feeds from tbl_posts, tbl_events, and tbl_shares. To implement ajax pagination that loads 10 items at a time when scrolling, I need a single query to fetch the LATEST F ...

Tips for presenting JSON date in JavaScript using Google Chart

I am in urgent need of assistance with this issue. I am trying to display the date from PHP JSON data retrieved from my database in a Google Chart using JavaScript. Below is the PHP code snippet: $data_points = array(); while($row = mysqli_fetch_array($r ...

During operational hours, an Ajax request may cause interruptions to the website's functionality

Having an issue with a large ajax request: I am querying a PHP file that makes some cURL requests, taking 15-20 seconds to complete and then returning JSON on my webpage. It's a standard ajax request, but I found a strange bug. While the ajax query i ...

Every time I attempt to create a detail page for a table, I am consistently greeted with an error message

Error: Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /var/www/2909kher/entabell/detaljer.php on line 23 <!doctype ...

Simultaneous execution of PHP form action and jQuery validation

When I try to execute my jQuery validation and PHP form, both actions are happening simultaneously. This means that validation errors are being displayed while the PHP form action is also being executed. Below is the complete code snippet. The jQuery form ...

Retrieve content from Wordpress blog including image preview

Can someone help me find a PHP script that can import posts from my WordPress blog and display them on another website, complete with a thumbnail of each blog post? Thank you in advance for your assistance! ...

I received incorrect JSON data

Take a look at my PHP code for encoding JSON data from MySQL database. Check out the URL . I validated the JSON data using JSONLint, which showed it as valid. However, instead of receiving the data in JSON format, I got the result [false]. Can anyone hel ...

What is the best way to reference a PHP file located outside the same directory as the main PHP file?

My current file structure looks like this: Wamp>www>Newlinks CSS (folder) header.php footer.php Profiles (folder) MainPHPfile.php I'm trying to include the header and footer files into MainPHPfile.php, but it's not working ...

Using a Select Query to Retrieve Multiple Rows from a Join Table in a Collection in Magento

Is it possible to execute a Select Statement in _preparecollection within Magento when the main table is joined with another table that has 2 rows containing 1 parent ID? The current tables available are: Main Table: https://i.stack.imgur.com/DWrep.png ...

How can a variable be passed to route.php from middleware in Laravel 5.2?

I have created a middleware and I need it to pass the variable $role to the route.php file. public function handle($request, Closure $next) { if ($this->auth->check()) { $role= "normal"; $user_roles = AssignedRoles::join(&ap ...

Combining JS and PHP for secure function escaping

Looking for a solution to properly escape quotes in generated PHP Javascript code. Here is an example of the current output: foreach ($array as $element) { echo '<a onClick="myFunctionTakesPHPValues('.$element[0].','.$element[1] ...

Retrieve the property of a class while inside another class that was instantiated within the original class in PHP

Explaining this using the correct terms can be challenging, so maybe an example would be more effective... $main = new MainClass(); $main->performAction(); class MainClass { var $x; var $y; var $z; var $eventProcessor; function ...

Generating AWS presigned URLs for objects stored in an S3 bucket

Our team uploads various types of content to a secure S3 bucket. When we generate and access presigned URLs for MP4 videos and images, everything works smoothly in the browser. However, when trying to access SWF and PDF files, the browser prompts us to dow ...

What is the best way to keep a selected item in a dropdown list using PHP?

I am encountering an issue with three drop down lists where the selected item is not retained after the form is submitted. For example, when I select '09' in one of the drop down lists and submit the form, it should still display '09' ...

Boost Engagement with the jQuery PHP MySQL Like Feature

Seeking assistance in creating a like button with PHP, MySQL, and jQuery. I'm encountering an error but unable to pinpoint its source. Can anyone provide guidance? The project involves two pages: index.php & callback.php INDEX $k = 1; //POST ID $n ...