0

Until now, I used to put absolute URLs in my included PHP files. For example in navbar.php, with a link to the services page: href="http://domain.com/services.php"

Since navbar.php is included in different directories, I had to use an absolute URL.

Problem is that when I'm testing the site locally using wamp server, this points me to the live site, which is not what I want.

What is the best practice for URLs in included PHP files?

I'm looking for something like 'root/thefile.php', where root can be either the domain (when the site is live) or localhost (when building and testing the site locally).

  • http://php.net/manual/en/reserved.variables.server.php SERVER_NAME should help you – Franz Gleichmann Oct 14 '16 at 08:39
  • or relative paths work too. http://stackoverflow.com/questions/17407664/php-include-relative-path – online Thomas Oct 14 '16 at 08:41
  • That is not even an "absolute URL" you used before. URLs are _always_ absolute per definition, but yours is just a string that _might_ be interpreted as the combination of a hostname and a path. It lacks the scheme (protocol) that is mandatory for a URL. – arkascha Oct 14 '16 at 08:41
  • 1
    A `path` usually is a better alternative, and typically one should prefer relative paths, since they allow flexibility in hierarchy, so it makes your code more portable. – arkascha Oct 14 '16 at 08:41
  • Ah, I see you changed the "URL" you posted to a valid version ;-) – arkascha Oct 14 '16 at 08:43

2 Answers2

1
$_SERVER['HTTP_HOST']

This will give you the root url ex.(domain.com)

So you could do use this:

echo 'http://' . $_SERVER['HTTP_HOST"];

And this would give you your url. You could also use

echo 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];

This will give you the complete url with the requests in it. ex (domain.com/thefile.php);

kerv
  • 315
  • 1
  • 2
  • 13
0
include ($_SERVER["DOCUMENT_ROOT"]."/file path");
Sinf
  • 123
  • 1
  • 4
  • 11