Publishing System Settings Logout Login Register
Relative Linking with Output Buffering
TutorialCommentsThe AuthorReport Tutorial
Tutorial Avatar
Rating
Add to Favorites
Posted on January 27th, 2007
2131 views
PHP Coding
What's this tutorial about?
In this tutorial I'll show you how to automatically relink your href, src, and action attributes to the current directory.

Say you had about 200-300 links that were like
href="/some-file.php"

That would link them to the root directory.
What if you moved the the files and the script into a different directory, and now you wanted to link them like this
href="/directory/some-file.php"


Well, we have an easy solution.
With some Output Buffering and a Regular Expression you can relink them to the "current directory"

Here's how
<?php
    ob_start('relink');
    function relink ($buffer) {
        $root = dirname($_SERVER['PHP_SELF']);
        return preg_replace('#(href|src|action)=("|'|)/#i', "1=2$root/", $buffer);
    }
?>
<a href="/omfg/onoz/">OMG onoz...</a>


What is Output Buffering? Output Buffering is registered by using
ob_start('some_function_name');

It passed the "output" to the function in the first parameter, called the "buffer".
So in this case, it passes our HTML link to relink(), which will allow us to handle it anyway we want.
What we do is do a preg_replace to change the links and make them relative to the current directory, which in my case is "tutorial-testing".
Try it out, throw the file around in different folders, you will notice it changes each time.

It's pretty easy, and probably the most handy trick there is when it comes to large websites, thanks for reading.
Dig this tutorial?
Thank the author by sending him a few P2L credits!

Send
HaloprO

I know how to Yo-Yo!
View Full Profile Add as Friend Send PM
Pixel2Life Home Advanced Search Search Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Pixel2life Homepage Submit a Tutorial Publish a Tutorial Join our Forums P2L Marketplace Advertise on P2L P2L Website Hosting Help and FAQ Topsites Link Exchange P2L RSS Feeds P2L Sitemap Contact Us Privacy Statement Legal P2L Facebook Fanpage Follow us on Twitter P2L Studios Portal P2L Website Hosting Back to Top