问题
I'm using WAMP and have a development site in the www directory. I want to use dirname(__FILE__)
to define the path to the server root.
Currently I'm using a config file which contains:
define('PATH', dirname(__FILE__));
I'm including the config file in in my header.php
file like this:
<?php require_once("config.php") ?>
Then, on my sub pages I use the constant PATH
to define the path by including header.php
.
<?php require_once("../inc/header.php"); ?>
However, my links are coming out like this:
<link rel="stylesheet" href="C:\wamp\www/css/style.css" />
What do I need to do to fix this? And since I'm including 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
?
回答1:
It looks like you just need to have
define('PATH', $_SERVER['SERVER_NAME']);
If you want to be super technical, you can do something like this instead.
define('PATH', str_replace($_SERVER['DOCUMENT_ROOT'], $_SERVER['SERVER_NAME'] . '/', dirname(__FILE__)));
On a side note, and more importantly, you don't actually need them. This will work.
<link rel="stylesheet" href="/css/style.css" />
When a href begins with a directory separator, it is considered relative to the document root, not the current working directory.
回答2:
__FILE__
is a filesystem path, not an URL path. I think you may be getting confused about which you need. To include php files or move things around, youll want to use the filesystem path. To create URLs to resources youll want to use the URL.
For filesystem stuff you can use what the dirname(__FILE__)
. So in your front controller or top level entry points if youre not using the front controller pattern you might have things like:
define('ROOT_PATH', dirname(__FILE__));
define('INC_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'includes');
As far as asstes go (css, images, js) i like to keep these in a single location at the 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 develop in subfolders on your local machine or testing server, but its easily avoided by using Virtual Hosts so that every site has its own file structure completely separate form others.
回答3:
$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__)))):'';
来源:https://stackoverflow.com/questions/9337731/dirname-file-on-localhost