PHP absolutely relative links

After there were some issues importing a WordPress site from a live server to a local server so we could work on it without fear of it breaking (it needs some pretty extensive back-end reorganization) I decided to solve the problem of mixed absolute and relative links my simply making them all relative. This works great in theory but in practice has some problems, for instance some of the classes call, and are called, from multiple location in the directory tree. PHP can handle this but when your trying to include an HTML image or javascript that can be a problem. Lets see if I can explain this problem a little better.

You have a class with a function that generates a form, it is stored on the root level as forms.class.php. You call this form from multiple locations, on the signup page also on the root directory located at signup.php and on the account modification page located at /account/index.php. The function uses a javascript file that is located at /js/form.js. If you call that file in the forms.class.php function via js/form.js it will work great on your signup.php file on the root of your server, but on /account/index.php it will 404, not being able to find it. Thats what this bit of code handles.


Place this on the top of the file thats displaying and then you can use the PHP definition ROOT in the class for the javascript file. On the root level of the server ROOT will be blank, and the link will still work just fine, but in the account/index.php page ROOT will be ../ which will tell the browser to look back one directory and then it will be able to find the file.

This is still a pretty sparsely tested little clip (just around a few folder in a test server) and there’s probably a better way to do it, but until I get a chance to sit down with the WordPress installation at work and test it out it is what it is. There are other improvements that can be done (like making it a function so your not locked into the current value making it not always go back to root) but for now it’s doing what I wanted it to do. I’ll make some improvements to it and update the snippet here and and snipplr accordingly.

Also, I’m sure theres a better way to do this, this is just the first solution that came to mind and I decided to roll with it. If there is a simpler method (not involving /htaccess or anything link that, simple PHP) that I find to do this then I’ll update accordingly