How can I execute a block of code in PHP once a day in the main template file? Non cron

I have a block of PHP code that generates a sitemap.xml file. The problem is that it generates a file every time the site page is loaded. The code is in my main template file.

How can I tell PHP to only execute this code once a day and not every time the template is loaded?

I don't want to use the cron tab because the code needs to be in the template file. The template file is pulled for multiple domains in one account. Therefore, I need to put a condition on the block of code that says only run this code when a page is loaded but only during a certain time frame each day, like from 12 noon to 4pm or something like that


I know what cron is for, but it needs to be done in PHP.


So here is what I came up with based on the answer Travesty3


$time  = time();
$sitemap = $_SERVER['DOCUMENT_ROOT'].'/sitemap.xml';
if ($time - filemtime($sitemap) >= 1*24*60*60) { // 1 days

(generate sitemap code here)



This works great. The sitemap is now generated only once a day, only if the site has at least 1 visitor per day.

But if the site has a lot of traffic, which was my initial concern for doing this in the first place, would it not check filemtime

the sitemap.xml file causing almost the same amount of server overhead as generating the sitemap for every request?


source to share

1 answer

You can check filemtime

in the generated file and only generate it on page load if it is over 24 hours old.

Alternatively, you can use cron to execute a PHP script or call a url. And there is.



All Articles