views:

31

answers:

3

In my php script I created a constant variable that defines the base url to be put in my hyperlinks, but do I really need this?

Here is an example of what I mean.

I have this:

 // base url is only defined once and reused throughout
 define("__BASE_URL","http://localhost/test1/");
 print '<a href="'.__BASE_URL.'index.php?var1=open/>Open</a>';

(I have a lot of these spread throughout my script.)

I tried this and it works:

 print '<a href="index.php?var1=open/>Open</a>';

So which way is the proper way on doing this? I noticed the second way even works on loading images, css, and javascript files.

+1  A: 

It depends. Without the __BASE_URL, your link will be relative to the current document. In your case, that means index.php must be in the same directory as the file that has the index.php link on it.

If you have the __BASE_URL, then the link will work no matter where its containing file is located (i.e. doesn't have to be in same directory as index.php).

Another option is to use a starting slash only. Then your link will be relative to your domain root:

print '<a href="/index.php?var1=open/>Open</a>';

In other words, the above link would point to http://localhost/index.php.

Pat
A: 

It sounds like your question is regarding absolute vs relative URLs. Are you going for portability? It's generally best to use relative URLs, especially if you plan to work in a test environment and then later transfer files to production.

MattB
+1  A: 

It really comes down to how you're structuring your site. Relative URLs are great (by doing href="index.php" you're reallying saying href="./index.php"), but they can start to become messy when you begin spreading pages over multiple directories.

Personally I like to base all of my relative URLs off of the root directory, meaning that all of my URLs start with a slash ('/'). That way it doesn't matter if my script is in / or /admin, as I will always have a constant reference point - the document root - as opposed to some relative directory in the structure.

Your first example, storing document paths in variables, really starts to come in handy when you begin developing larger systems where you want the paths to be configurable. For example, maybe you want your system admins to be able to define where images are pulled from, or where the cached downloads are.

So really consider your use cases and size of your system.

Also keep in mind that if you ever move the script to another server that your URLs and directory structures may change, which could cause havoc (ex., you might have your script moved to a different subdomain, into the document root, etc.). A lot of people will drop in Apache's mod_rewrite in this case.

Sam Bisbee