简体   繁体   中英

Auto detect site root path on UA site and production site with php

Here is the case, I would like to call an image from the site root (instead of using ../),

production site: http://www.example.com/details/
the image path would be /img/header/logo.png

on UAT http://www.testingserver.com/abc-ver3/details/
the image path would be /abc-ver3/img/header/logo.png

on local http://localhost/abc/
the image path would be /abc/img/header/logo.png

I am currently using a stupid way to get the site root:

in the file /includes/layout.php:

<?php $siteroot = '/abc'; ?>
<img src="<?php echo $siteroot ?>/img/header/logo.png" alt="ABC Co.">

and I change the path manually when deploy to another server

is there anyway to auto detect the root path?

Sorry for stupid questions but I don't find the way.

A quick and dirty,

$server     = $_SERVER['SERVER_NAME'];
$siteroot       = 'details'; //default val

if(substr_count($server, 'example.com.'))
    $siteroot   = 'details';
else if(substr_count($server, 'tetsingserver.com'))
    $siteroot   = 'abc-ver3/details';
else
    $siteroot   = 'abc';

return $siteroot;

This is a hacky way of doing this.

Ideally this would go into a bootstrap. OOP for the win.

Happy coding

I just found another dirty way which works on my local, not sure if it works on production site:

in /includes/layout.php

$path = dirname(__FILE__); //returns "C:\wamp64\www\abc\includes" 
$path = str_replace("\\","/",$path) //returns "C:/wamp64/www/abc/includes"
$path = str_replace($_SERVER["DOCUMENT_ROOT"],"",$path) //returns "/abc/includes"
$siteRoot=str_replace('/includes','',$path) //returns "/abc"


or in short:

$siteRoot=str_replace('/includes','',str_replace($_SERVER["DOCUMENT_ROOT"],'',str_replace("\\","/",dirname(__FILE__))));

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