«

»

Apr 14

PHP Rewrite URLs using Output Buffer

I recently was in need of replacing URLs to SEO friendly ones, the only hiccup was I wanted to maintain the PHP $_GET params in the source code. As this is tried and true, and mod_rewrite can have its hiccups now and then. So after some research I found a solution that fit me perfectly. Using PHP’s output buffer I can utilize a callback function and a few preg_replace() functions to achieve all the necessary rewrites. And if for some reason I do not want to have rewrites enabled, I can comment out the callback and all my PHP URLs are back in place with no need for code editing. Here’s my example.

<?php

// initialize output buffer to compress page.
// note: I recommend using 'ob_gzhandler' for pages >5kb. Any smaller its not worth it.
ob_start('ob_gzhandler');

// call the rewrite function.
HandleRewrite();

// do your page stuff...
echo '<a href="index.php?subpage=MYPAGE">Hello World!</a>';

// handle the URL rewriting
function HandleRewrite()
{
	// rewrite URLS from output buffer
	// note: it is IMPERATIVE this function is ABOVE the ob_start('rewrite') callback.
	function rewrite($buffer)
	{
		// this preg_replace changes "mysite.com/index.php?subpage=TEST to mysite.com/TEST
		$buffer = preg_replace('/index.php\?subpage=(\w)/is', "$1", $buffer);
		return $buffer;
	}
	
	// start the output buffer for rewriting ('rewrite' being the callback function)
	ob_start('rewrite');
}

?>

Utilizing this method makes it so your entire page can be re-written to any mod_rewrite (or whatever SEO utility you use) without search/replace of every link in your code.

As always, if you have any questions or comments, please reply.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>