views:

48

answers:

3

Is there an easy way to swap a file url based on domain name?

I've acme.com & acme.co.uk site domains which require different header graphic but are otherwise identical content. Rather than managing two sets of files and CMS, is there a JS/php script or other method to change the header graphic url dynamically based on which domin name is accessed? Site is basic XHTML & CSS.

A: 

You should be able to do this with PHP by using if statement.

http://php.net/manual/en/reserved.variables.server.php $_SERVER variable would come in handy here.

And then, you just have to print/return you desired image path.

I can give you a full example too, but try for yourself, it's well worth it.

Tom
+3  A: 

With PHP

Use $_SERVER['HTTP_HOST'] to get your domain and then do a switch-statement to change the image-variable.

<?php
switch($_SERVER['HTTP_HOST']) {
    case 'acme.com':
    case 'www.acme.com':
        $image = "acmecom.jpg"
    break;
    case 'acme.co.uk':
    case 'www.acme.co.uk':
        $image = "acmecouk.jpg"
    break;
    default:
        $image = "default.jpg"
    break;
}
?>

If your using www before acme.com you have to change the address from "acme.com" accordingly to "www.acme.com". Same for .co.uk.

In your header-image you then echo the path to the image like this:

<img src="path/to/folder<?php echo $image;?>" alt="header-image" />

Tim
Thanks for the code Tim, I'll try that, just checking that is PHP?
Wes79
it would be nice to handle www. prefix as well
Col. Shrapnel
@Wes79, it is php. Check the `$_SERVER` variables, at: http://php.net/manual/en/reserved.variables.server.php
David Thomas
I added to check for the www as well. And yes, its PHP
Tim
A: 

Because I can't stand Tim's coding style...

<?
$host = preg_replace('~^www\.~','',$_SERVER['HTTP_HOST']);
$headerpic = basename($host).".jpg";
if (!is_readable($_SERVER['DOCUMENT_ROOT'])."/images/header/".$filename) {
  $headerpic = "default.jpg"
}
?>
<img src="/images/header/<?=$headerpic?>">
Col. Shrapnel
Thanks for your help, I placed the php above body tag in php test page, image tag within the body tag and correct paths, it seems to create a blank frameset but I haven't been able to get it working. I think the fact that the .co.uk address is re-directing to the site hosted on the .com address could mean the php sees the same domain either way :(My host can add meta tags as part of the re-direct, could the meta tag be used to change the .co.uk image, think I've seen something similar before?
Wes79
@Wes79 First of all you have to check $_SERVER['HTTP_HOST'] variable by echoing it. To ensure it doesn't reflect actual requested domain. If it doesn't you can use javascript to read meta tag property
Col. Shrapnel