skip to Main Content
Menu

Getting Current host and current folder in PHP

There are times when clients or we start of projects in what i call a development server or a local server or a server that is used for testing. This server can either be local or on the internet.

In development, we are sometimes faced in a situation wherein we would want to provided links that are pre-determined by php so all we have do is to call these links, usually defined as values in variables.

Ex. <a href="<?php echo $homepagelink; ?>">the homepage</a>

To assign a value to the “$homepagelink”, we would be using two built in functions in PHP $_SERVER[‘HTTP_HOST’] and basename(dirname(__FILE__)). Now don’t take my word for it, because there are other solutions that might work even better and might even be shorter in terms of code.  Anyway here is the short snippet i use for this purpose.


// to get the current domain or the http://www.domain.com/
$domain = $_SERVER['HTTP_HOST'];
// to get the current directory or folder, this is assuming that you are just one folder deep.
$folder=basename(dirname(__FILE__));
$homepagelink= "http://" . $domain ."/".$folder;

So, if you’re host is on say.. http://www.example.com and your folder is named dev, Placing this script inside any php in the folder dev and echo-ing the variable $homepagelink would give us the value of http://www.example.com/dev.  Neat huh?

Alphonse

Editorial Staff at ETN Multimedia is led by Alphonse Tan. Page maintained by Alphonse Tan

Back To Top