March 20, 2012

How to get folder root from url?

Question by Earvin Bryan S. Co

How do you get the root folder from a php file?

For example

URL: http://localhost/project_name/

Result: return “project_name”

Answer by Starx

Use the parse_url() function for this

$url = $_SERVER['REQUEST_URI']);
$urlParse = parse_url($url);

echo $urlParse['hostname'];

However, this will only work, if you are using a webserver, for these type of url

http://www.mydomain.com

If you want this to work on a localhost, add some few lines

$url = $_SERVER['REQUEST_URI']);
$urlParse = parse_url($url);

$path = explode('/',$urlParse ['path']);
echo $path[1]; //gives project_name in your case

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!