PHP: How to get working website path and directory name?

This tutorial shows site name, working directory name, etc. with the help of $_SERVER variable.

Let us suppose, that our website is:
http://wwww.example.com/test/admin/index.php

1) Get name of the website

echo $_SERVER['SERVER_NAME'];

OR,

echo $_SERVER['HTTP_HOST'];

This will print: www.example.com

2) Get the path of the page you are working on

echo $_SERVER['PHP_SELF'];

This will print: /test/admin/index.php

3) Get only the directory name of the page you are working on

echo dirname($_SERVER['PHP_SELF']);

This will print: /test/admin

If you want to omit the ‘admin’ directory as well then you can use dirname() function two times:

echo dirname(dirname($_SERVER['PHP_SELF']));

This will print: /test

Finally:

echo "http://".dirname($_SERVER['SERVER_NAME']."".$_SERVER['PHP_SELF']);

This will print: http://www.example.com/test/admin

Thanks.