Autodetect and serve <base element based on local or doma

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Autodetect and serve <base element based on local or doma

Post by JAB Creations »

The <base element defines the base path (from which the relative paths to scripts and stylesheets can be defined). I'd like to make a simple script that will have the JS/CSS load correctly regardless of whether the page is located at localhost or a domain name. For example I work on versions of my site so the absolute/relative paths are different locally (localhost) then on the domain name when I upload my work. Having a PHP script to set the base path based on whether the page is loaded from localhost or the domain name would allow me to not have to create two separate instances...which would be messy.

Here is what I would have the clientside code look like for localhost...
<base href="http://localhost/Version%202.8/" />
<link href="themes/classic/style.css.php" media="screen" rel="stylesheet" type="text/css" />
So the absolute path to the main stylesheet on my localhost would be...
http://localhost/Version%202.8/themes/c ... le.css.php

On my domain name it would look like this...
<base href="http://www.jabcreations.net/" />
<link href="themes/classic/style.css.php" media="screen" rel="stylesheet" type="text/css" />
So the absolute path to the main stylesheet on my domain name would be...
http://www.jabcreations.net/themes/clas ... le.css.php

I could figure out the PHP script fine but I am curious what I should use to determine if the page is being loaded at localhost or a specific domain name? Thanks for your replies!
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

Ah, I found what I needed! $_SERVER['SERVER_NAME']

Here is the PHP code...

Code: Select all

if ($_SERVER['SERVER_NAME'] == "localhost")
{
$path = 'http://localhost/Version%202.8/';
}
else if ($_SERVER['SERVER_NAME'] == "jabcreations")
{
$path = 'http://www.jabcreations.net/';
}

echo '<base href="';
echo $path;
echo '" />' . "\n";
Post Reply