简体   繁体   中英

Get root url of the site in PHP

Consider my project directory structure as follows,

-public_html
  -projects
    -folder1
      index.php \\code is written here
    +folder2
  +downloads

I am trying to get the root directory through $_SERVER['DOCUMENT_ROOT'] , but it seems the returned string is not in the form I expect.

My directory inside my website is (basically in) public_html/projects/folder1 . Using document root, the returned string is as follows when implemented on a website, /home/site_name/public_html which is not going to work if the link is to be shared, cause I am using it to store the file in a directory. So, I want something like it should return, www.site_name.com/downloads

The __DIR__ is giving the whole document path from where it is called( folder1/index.php ), but I want to get into the main folder ( public_html/downloads ), not in the same folder as the index file is.

Are there any other php functions that can help to reach the downloads folder in public_html and which can be accessed like, www.sitename.com/downloads/...

To return the folder of current php file, use this script.

$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
$dir = $_SERVER['SERVER_NAME'];
for ($i = 0; $i < count($parts) - 1; $i++) {
 $dir .= $parts[$i] . "/";
}
echo $dir;

You want to use $_SERVER['SERVER_NAME'] to get the root URL of the site. You can use this to get a URL to your downloads folder.

$downloads_url = $_SERVER['SERVER_NAME'] . '/downloads/';

constants.php:

define('PROTOCOL',(!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://',true);
define('DOMAIN',$_SERVER['HTTP_HOST']);
define('ROOT_URL', preg_replace("/\/$/",'',PROTOCOL.DOMAIN.str_replace(array('\\',"index.php","index.html"), '', dirname(htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES))),1).'/',true);// Remove backslashes for Windows compatibility

Then, in the the index of the project use it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM