You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WHMCS首页的Smarty模板中添加指定HTTP响应头?

在WHMCS首页添加自定义HTTP响应头的解决方法

Smarty 3+默认禁用了原生PHP标签的解析,所以你直接在header.tpl里写header()函数只会被当成普通文本输出,不会执行。下面提供两种可行的解决方式:

方法一:使用WHMCS钩子(推荐)

WHMCS的钩子机制可以让你在页面渲染前执行PHP逻辑,非常适合处理这类请求头设置的需求:

  1. 在WHMCS的includes/hooks目录下新建一个钩子文件,比如cache_header_hook.php
  2. 写入以下代码:
<?php
add_hook('ClientAreaPage', 1, function($vars) {
    // 判断当前是否为公共首页
    if ($vars['templatefile'] == 'homepage') {
        header("Cache-Control: public, max-age=86400, must-revalidate"); // HTTP 1.1
        header("Pragma: cache"); // HTTP 1.0
    }
});

这个钩子会在客户端页面加载时触发,当检测到当前页面是首页时,自动添加对应的响应头,完全避开Smarty模板的限制。

方法二:自定义Smarty函数(模板层实现)

如果一定要在header.tpl里处理,可以通过注册自定义Smarty函数来实现:

  1. 在WHMCS的includes目录下创建custom_smarty_functions.php文件,内容如下:
<?php
function smarty_function_set_cache_header($params, $smarty) {
    $maxAge = isset($params['max_age']) ? $params['max_age'] : 86400;
    header("Cache-Control: public, max-age={$maxAge}, must-revalidate");
    header("Pragma: cache");
}
  1. 在includes/bootstrap.php文件的末尾添加以下代码,注册这个自定义函数:
require_once __DIR__ . '/custom_smarty_functions.php';
if (isset($smarty)) {
    $smarty->registerPlugin('function', 'set_cache_header', 'smarty_function_set_cache_header');
}
  1. 最后在header.tpl里调用这个函数:
{if $templatefile == 'homepage'}
    {set_cache_header max_age=86400}
{/if}

注意:相比钩子方案,模板层添加逻辑会降低代码的可维护性,优先推荐使用钩子方法。

内容的提问来源于stack exchange,提问作者jsidigital

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:01:20