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
?
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.
__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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With