bikey77
bikey77

Reputation: 6672

How can I make all paths relative to document root?

My project dir structure is

/admin
    L index.php
/includes
    L scripts.php
    L common.php
/css
/js
index.php
header.php
footer.php
...

In index.php I include /includes/scripts.php which contains references to various css files in /css dir like such:

<link rel="stylesheet" type="text/css" href="css/jquery.alerts.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />

etc...

Everything works fine when including /includes/scripts.php from the document root but if I include scripts.php from inside a different dir, ie /admin, then the paths are no longer valid and the inclusion of all files referenced fails. How can I make all paths relative to document root no matter where I call them from within my project?

Upvotes: 1

Views: 2895

Answers (2)

Kai Qing
Kai Qing

Reputation: 18833

<link rel="stylesheet" type="text/css" href="/css/jquery.alerts.css" />

add a slash before the url to read from web root. Keep in mind there is a difference between document root and web root. document root could resolve to something like /home/sites/www/yourdomain.com/

Adam's answer may be more precise to your needs, but in general, why are you writing your paths to not be relative to the web root if that's your goal? It seems your issue is more of a fundamental organizational error that could be resolved by employing standard practice over a work around

Alternatively, you can define a base url variable and use it to write out these links:

<?php
$base_url = 'http://www.yoursite.com/';
// $base_url = 'http://dev.yoursite.com/'; if you work locally and have defined this in your vhosts file
?>

<link rel="stylesheet" type="text/css" href="<?php echo $base_url; ?>css/jquery.alerts.css" />

Upvotes: 2

Adam Zielinski
Adam Zielinski

Reputation: 2874

use <base href="/"/>

check this question for more information: Is it recommended to use the base html tag

or manually rework your URLS to relative to root like /css/style.css

Upvotes: 2

Related Questions