How to get absolute path to public_html folder

2.4k views Asked by At

I'm a little confused about absolute paths when searching in the questions. I have a php project that includes a Header.php file which is the header for first level php files. To avoid adding another header, I want to make that work for the inner levels, too. For example use it in a php file that is included in another folder of project. To do this, I wana get the absoute path to my public_html folder and use that in my Header.php. How can I get it?

4

There are 4 answers

3
Sougata Bose On BEST ANSWER

Use / at the start.

include('/header.php');

This will always include the header.php from the root folder.

1
Gildas Ross On

You can got the absolute path of your current script file by this way :

$absolute_path = dirname(__FILE__);

You can see all of the Magic constants here : http://php.net/manual/en/language.constants.predefined.php

0
ZHANG WEI On

I think what you need is $_SERVER['DOCUMENT_ROOT']

0
tsig On

None of the above worked for me in different servers, so had to write the following function:

echo  "public_html absolute path:".public_html();
function public_html() {
  $path=getcwd();
  if (!strpos($path,'public_html')) $path=$_SERVER['PHP_SELF'];
  $awords= explode('/', $path); 
  $public_html="";
  foreach ($awords as  $word)   {
     $public_html.=$word."/";
     if ($word=='public_html') break;
  }
return  substr($public_html,0,-1);
}