Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wordpress with Redis using PHPRedis from https://github.com/nicolasff/phpredis - Based on blogpost from Jim Westergren http://www.jimwestergren.com/wordpress-with-redis-as-a-frontend-cache/
<?php
/*
Author: Hans2103
credit: Jim Westergren, Jeedo Aquino & Flynsarmy
File: index-with-redis.php
Updated: 2013-05-27
This is a redis caching system for Wordpress based on Redis connection using PHPRedis.
https://github.com/nicolasff/phpredis
Originally written by Jim Westergren but improved by Jeedo Aquino to connect with PRedis.
https://github.com/nrk/predis
see more here: www.byte.nl/blog/wordpress-with-redis
some caching mechanics are different from jim's script which is summarized below:
- cached pages do not expire not unless explicitly deleted or reset
- appending a ?c=y to a url deletes the entire cache of the domain, only works when you are logged in
- appending a ?r=y to a url deletes the cache of that url
- submitting a comment deletes the cache of that page
- refreshing (f5) a page deletes the cache of that page
- includes a debug mode, stats are displayed at the bottom most part after </html>
for setup and configuration see more here:
www.jeedo.net/lightning-fast-wordpress-with-nginx-redis/
use this script at your own risk. i currently use this albeit a slightly modified version
to display a redis badge whenever a cache is displayed.
implementation:
- Rename WordPress index.php to index.php.bak or any name that will indicate that this is the original index.php.
- copy this file wp-index-redis.php to index.php.
- That's it
*/
$start = microtime(); // start timing page exec
// from wp
define('WP_USE_THEMES', true);
define('R_SERVER', '<servername>'); // The server of your Redis database
define('R_PORT', <portnumber>); // The port to your Redis server
define('R_PASSWORD', '<password>'); // ...and password
define('R_PREFIX_KEY', ''); // Redis key prefix
define('R_CLOUDFLARE', false); // true or false if you're using Cloudflare or not
define('R_DEBUG', true); // true or false if you wish to see execution time and cache actions or not
// allow IP-addresses for debug information
$ip = $_SERVER['REMOTE_ADDR'];
$allowed = array(
'1.1.1.1', //
'2.2.2.2', //
);
// exclude some pages from caching
$exclude = array (
'/cart/', // woocommerce Cart
'/my-account/', // woocommerce My Account
'/checkout/', // woocommerce Checkout
);
// needle & haystack -> needed to exclude pages from caching
// see http://stackoverflow.com/a/9220624
function strposa($haystack, $needle, $offset=0) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $query) {
if(strpos($haystack, $query, $offset) !== false) return true; // stop on first true result
}
return false;
}
// if cloudflare is enabled
if (R_CLOUDFLARE) {
alert('now');
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
}
}
// Redis connection
$redis = new Redis();
$redis->connect(R_SERVER,R_PORT,2.5);
$redis->auth(R_PASSWORD);
// Remove all keys from all databases
//$redis->flushall();
// Remove all keys from the current database
//$redis->flushdb();
// init vars
$cached = 0;
$domain = $_SERVER['HTTP_HOST'];
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$url = str_replace('?r=y', '', $url);
$url = str_replace('?c=y', '', $url);
$dkey = md5($domain);
$ukey = md5($url);
// check if page isn't a comment submission
(($_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0') ? $submit = 1 : $submit = 0);
// check if logged in to wp
$cookie = var_export($_COOKIE, true);
$loggedin = preg_match("/wordpress_logged_in/", $cookie);
// check if a cache of the page exists
if ($redis->hexists(R_PREFIX_KEY.$ukey, $dkey) && !$loggedin && !$submit && !strpos($url, '/feed/')) {
echo $redis->hget(R_PREFIX_KEY.$ukey, $dkey);
if (!R_DEBUG) exit(0);
$msg = 'this is a cache';
// if a comment was submitted or clear page cache request was made delete cache of page
} else if ($submit || substr($_SERVER['REQUEST_URI'], -4) == '?r=y') {
require('./wp-blog-header.php');
$redis->hdel(R_PREFIX_KEY.$ukey, $dkey);
$msg = 'cache of page deleted';
// delete entire cache, works only if logged in
} else if ($loggedin && substr($_SERVER['REQUEST_URI'], -4) == '?c=y') {
require('./wp-blog-header.php');
$redis->flushdb();
$msg = 'domain cache flushed';
// if logged in don't cache anything
} else if ($loggedin) {
require('./wp-blog-header.php');
$msg = 'not cached';
// if page is excluded from caching
} else if (strposa($url, $exclude)) {
require('./wp-blog-header.php');
$msg = 'not cached';
// cache the page
} else {
// Start buffering
ob_start();
// Output stuff
require('./wp-blog-header.php');
// Get value of buffering so far
$getContent = ob_get_contents();
// Stop buffering
ob_end_clean();
// Do stuff to $getContent as needed
//
// Use it
echo $getContent;
// Store to cache only if the page exist and is not a search result.
if (!is_404() && !is_search()) {
// store html contents to redis cache
$redis->hset(R_PREFIX_KEY.$ukey, $dkey, $getContent);
$msg = 'cache is set';
}
}
$end = microtime(); // get end execution time
// show messages if debug is enabled
if (R_DEBUG && in_array($ip, $allowed)) {
//if (true) {
// You should move this CSS to your CSS file and change the: float:right;margin:20px 0;
// Mind that if the page is served through Cloudflare you might view a cached page from Cloudflare.
echo "<style>#redis_powered{margin:20px auto;background:url(http://images.staticjw.com/jim/3959/redis.png) 10px no-repeat #fff;border:1px solid #D7D8DF;padding:10px;width:240px;}
#redis_powered div{text-align:center;font:10px/11px arial,sans-serif;color:#000;margin-left:100px;}</style>";
echo "<a href='http://www.byte.nl/blog/wordpress-with-redis' style='text-decoration:none;'><div id='redis_powered'><div>Page generated in<br/> ".t_exec($start, $end)." sec<br/>".$msg."</div></div></a>";
}
// time diff
function t_exec($start, $end) {
$t = (getmicrotime($end) - getmicrotime($start));
return round($t,5);
}
// get time
function getmicrotime($t) {
list($usec, $sec) = explode(" ",$t);
return ((float)$usec + (float)$sec);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.