PHP Echo Tutorials

Rewriting URLs

Written by phpecho.com   

If you're developing a website in a sub-directory, this little tutorial could be a lot of use to you.

When I make a website, or code a design, I like to link to everything (CSS and JavaScript documents, for example) with a prefix slash. Now before this tutorial came about, that would just make all links and source requests fall to the root directory. But with this tiny function, you can fix all of that mess!

First of all, your document needs to be a PHP file. That means it has to have a .php, .php3, .php4, or .php5 extension.

To start this off, we'll imagine that the file we're creating is in a directory called /example/. We need to first start Output Buffering, by putting this at the VERY TOP of our file.

  <?php
    ob_start('ob_gzhandler');
    ob_start('rewrite');

Notice that there are two instances of ob_start(). The first initializes GZIP compression, making file load times much quicker. The second defines a buffer function that we must place right after the code we just typed out.

  function rewrite ($buffer) {

Here comes the actual code. First in the function, we need to find out the root of the current folder. This is what will be placed in front of all URL's that are prefixed with a slash. Essentially, it redefines the root directory for this file.

  $root = ereg_replace('/$', '', dirname($_SERVER['PHP_SELF']));

Now we need to define two more variables; $s (search), and $r (replace). Well be search and replacing with REGEX, as always, so you shouldn't edit these two variables unless you really know what you're doing.

  $s = array('#(href|src|action)="/([^"]+)"#', '#url\(\'/([^\']+)\'\)#');
    $r = array("\\1=\"$root/\\2\"", "url('/$root/\\1')");

Lastly, we need to add the replacing function and finish up the rewrite function.

  return preg_replace($s, $r, $buffer);
    }
    ?>

Once that is at the top of your document, it will convert all URL's like this:

 <link rel="stylesheet" href="/css/main.css" />

To this:

 <link rel="stylesheet" href="/example/css/main.css" />

And that's all in this tutorial from phpecho.com. Thanks for reading!