PHP absolutely relative root

/ Published in: PHP
Save to your folder(s)

After an attempt to more a live site to a personal server for further work I ran across the problem of a mix of absolut and relative links making the local copy not work. Not wanting to manually have to change every single absolute to a relative (because some files are called from multiple sources leading to time consuming complicated conditional relative link) I looked for ways to simple "convert" my original absolutes to relatives and come up with this.

Basically, this adds the appropriate number of back links (../'s) so that it starts at your server root. This makes relative linking easier because they will always start from the same place no matter where you are or what file may be making the link.

This is just a first run of it, I know of some improvements that could be made (primarily, making it a class instead of a definition because once this is set it's stuck, causing it to work incorrectly at times) but this version works for basic sites.

Copy this code and paste it in your HTML
  1. define("ROOT",str_replace('/','../',str_replace('.','',preg_replace("~[^/.+]~","",substr(__FILE__, strlen( $_SERVER['DOCUMENT_ROOT']))))));


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.