Jump to content

Unexpected results with $_SERVER var for portable PHP


xtian

Recommended Posts

I'm working to make my code more portable when moving it between servers. I am trying to use the $_SERVER['SERVER_NAME'] global variable to change the page's URL whenever I move it.

 

<a href="<?php print $_SERVER['SERVER_NAME'].'/index.php';?>">LINK TO SERVER'S HOME PAGE</a>

 

This line is in a php page with this URL,

http://localhost/php/tests/link_test.php

 

However this is acting unexpectedly. The current directory of the file is being added before the server name and the link becomes,

http://localhost/php/tests/localhost/index.php

 

What am I doing wrong?

Chris

$_SERVER['SERVER_NAME'] is only 'localhost'

 

Because the href= syntax that you are using is for a relative URL, the browser prepends the URL of the current page.

 

You need to specify an absolute URL-

<a href="<?php print 'http://' . $_SERVER['SERVER_NAME'] . '/index.php';?>">LINK TO SERVER'S HOME PAGE</a>

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.