如何在主模板文件中每天执行一次PHP代码块?非cron [英] How to execute a block of code in PHP once per day in main template file? Non cron

查看:83
本文介绍了如何在主模板文件中每天执行一次PHP代码块?非cron的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP代码块,用于生成我的sitemap.xml文件。问题是,它会在每次加载网站页面时生成文件。



我如何告诉PHP只执行这段代码,每天一次,而不是每次加载模板?

我不想使用cron选项卡,因为代码需要在模板文件中。为同一帐户上的多个域拉取模板文件。所以我需要在代码块上写一个条件,说只有在页面加载时运行这个代码,但只在某一时间帧每天,例如从中午12点到下午4点或类似



我知道这是cron的用途,但需要在PHP中完成。



UPDATE



所以这是我想出的基础 Travesty3

  $ time = time(); 
$ sitemap = $ _SERVER ['DOCUMENT_ROOT']。'/ sitemap.xml';
if($ time - filemtime($ sitemap)> = 1 * 24 * 60 * 60){// 1天$ ​​b
$ b(在此生成站点地图代码)

}

这很好。



但是,如果网站有大量的流量,这是我原来的首先会考虑这样做,不会检查sitemap.xml文件的 filemtime 导致在服务器上产生与生成sitemap文件几乎相同的开销每个请求?

解决方案

您可以检查 filemtime ,只有在超过24小时后才会在网页加载时生成。



此外,您可以使用cron来执行PHP脚本或调用URL。所以也是这样。


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

How could I tell PHP to only execute this code say, once per day, instead of every time the template is loaded?

I don't want to use cron tab because the code needs to be in the template file. The template file is pulled for multiple domains on the same account. So 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 that is what cron is for, but need it done in PHP.

UPDATE

So this is what I came up with based on Travesty3 answer.

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

(generate sitemap code here)

}

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

But if the site has a lot of traffic which was my original concern for doing this in the first place, won't checking the filemtime of the sitemap.xml file cause almost the same amount of overhead on the server as generating the sitemap file on each request?

解决方案

You could check the filemtime on the generated file and only generate it on page load if it's over 24 hours old.

Also, you can use cron to execute a PHP script or call a URL. So there's also that.

这篇关于如何在主模板文件中每天执行一次PHP代码块?非cron的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆