June 12, 2012

absolute path source php

Question by Felix Perdana

This is maybe just a trivial question, but I don’t really know what is the best practice to include, says javascript, img, or css using absolute path

What I am really using right now is using the code like this

<?php
$prefix = '//';
$rootFolder = $prefix . $_SERVER['HTTP_HOST'];
?>

so then when i want to include something like jquery, I would just type the code like this

<script type="text/javascript" src="<?php echo $rootFolder ?>/jquery-1.7.1.min.js"></script>

is this good enough? Or should I modify the prefix to “http://” or maybe there is some better way using another superglobal variable and such?

thanks in advance 🙂

Answer by Starx

This question cannot be answered in a correct way, because absolute and relative paths, both have their own importance on a website.

For search engines, they dont like websites with absolute links to the same websites. The modern browsers nowadays already read the relative path with the websites current URL prefixed, unless “/” is used infront of an URL. So, it should not harm when you try to use a relative path as much as possible.

Another case is, If you application is extendable by multiple modules. Generally taking, an admin module and one user module. If these module share a common resource folder for JS, CSS and others then its useful and easy to create a relative paths.

Since, your question is concerned about accessing a resource from the root folder, you should be fine as it is i.e using relative paths.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!