Dirname (__ FILE__) on localhost

I use WAMP and have a development site in the www directory. I want to use dirname(__FILE__) to determine the path to the server root.

I am currently using a configuration file that contains:

 define('PATH', dirname(__FILE__)); 

I include the configuration file in my header.php file as follows:

 <?php require_once("config.php") ?> 

Then, on my auxiliary pages, I use the PATH constant to determine the path by including header.php .

 <?php require_once("../inc/header.php"); ?> 

However, my links come out as follows:

 <link rel="stylesheet" href="C:\wamp\www/css/style.css" /> 

What do I need to do to fix this? And since I include my constant in the header.php file, I don’t have access to the constant in the initial require_once("../inc/header.php"); . What other method can I use to find the root for header.php ?

+4
source share
3 answers

Sounds like you just need to

 define('PATH', $_SERVER['SERVER_NAME']); 

If you want to be supertechnical, you can do something like this.

 define('PATH', str_replace($_SERVER['DOCUMENT_ROOT'], $_SERVER['SERVER_NAME'] . '/', dirname(__FILE__))); 

On a side note, and, more importantly , you really don't need to. This will work.

 <link rel="stylesheet" href="/css/style.css" /> 

When href starts with a directory separator, it is relative to the document root, not the current working directory.

+8
source

__FILE__ is the path to the file system, not the URL. I think you might get confused about what you need. To include php files or move things, you want to use the file system path. To create URLs for resources, you want to use a URL.

For filesystem files, you can use dirname(__FILE__) . Therefore, if you do not use front controller templates, you can have things like:

 define('ROOT_PATH', dirname(__FILE__)); define('INC_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'includes'); 

As for asstes go (css, images, js), I would like to save them in one place in DOCUMENT_ROOT , so the path is always /css/path/to/file.css , regardless of where you are in the file structure. This can be a problem if you are developing subfolders on your local computer or test server, but it is easy to avoid using virtual hosts so that each site has its own file structure that completely separates the others.

0
source
 $server = str_replace('\\','/',$_SERVER['SERVER_NAME']); $server = (substr($server,-1)=='/'?substr($server,0,strlen($server)-1):$server); !defined('PATH')?define('PATH', 'http://'.str_replace($_SERVER['DOCUMENT_ROOT'],$server , str_replace('\\','/',dirname(__FILE__)))):''; 
0
source

Source: https://habr.com/ru/post/1397142/


All Articles