PHP中 简单的缓存怎么写 ?

PHP数据缓存常用页面缓存 静态缓存
php页面缓存主要用到的是ob系列函数,如ob_start(),ob_end_flush(),ob_get_contents()
静态缓存是指静态化,直接生成HTML或XML等文本文件,有更新的时候重生成一次,适合于不太变化的页面
给你个页面缓存的例子

function page_cache($ttl = 0)
{   
    $ttl = $ttl ? $ttl : PAGE_TTL;//缓存时间,默认3600s
    $contents = ob_get_contents();//从缓存中获取内容
    $contents = "<!--page_ttl:".(time() + $ttl)."-->n".$contents;
    //加上自定义头部:过期时间=生成时间+缓存时间
    file_put_contents(PAGE_FILE, $contents);//写入缓存文件中
    ob_end_flush();//释放缓存
}

 

转载于:https://my.oschina.net/feanlau/blog/968358

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的WordPress缓存插件示例: ```php <?php /** * Plugin Name: Simple Cache * Description: A simple caching plugin for WordPress. * Version: 1.0 * Author: Your Name * Author URI: https://yourwebsite.com/ */ // Define cache duration in seconds define( 'SIMPLE_CACHE_DURATION', 3600 ); // Enable caching for logged-in users define( 'SIMPLE_CACHE_LOGGED_IN', true ); // Check if page is cacheable function is_cacheable() { if ( is_admin() ) { return false; } if ( SIMPLE_CACHE_LOGGED_IN && is_user_logged_in() ) { return false; } return true; } // Get cache key function get_cache_key() { global $wp; $url = home_url( $wp->request ); return 'simple_cache_' . md5( $url ); } // Get cached content function get_cached_content() { $key = get_cache_key(); $content = get_transient( $key ); if ( $content ) { return $content; } return false; } // Cache content function cache_content( $content ) { $key = get_cache_key(); set_transient( $key, $content, SIMPLE_CACHE_DURATION ); return $content; } // Filter content before output function filter_content( $content ) { if ( is_cacheable() ) { $cached_content = get_cached_content(); if ( $cached_content !== false ) { return $cached_content; } $content = cache_content( $content ); } return $content; } add_filter( 'the_content', 'filter_content' ); ``` 这个插件会将页面缓存起来,以便下一次访问时可以更快地加载页面。缓存持续时间可以通过 `SIMPLE_CACHE_DURATION` 常量来设置。如果你想让已登录用户也可以使用缓存,可以将 `SIMPLE_CACHE_LOGGED_IN` 常量设置为 `true`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值