OK, the title is a little confusing but this is the structure of my web site:
/
|--header.php
|--page1.php
+--css
|--style.css
+--subsection
|--page2.php
+--functions
|--classes.php
Right, so both page1.php
and page2.php
will include
header.php
. This I do by just using the relative file path from whatever php page to the header.php.
header.php
itself includes other files; for example css/style.css
and functions/classes.php
.
I might include them like the following:
<link rel="stylesheet" href="css/style.css">
<?php require_once("functions/classes.php"); ?>
This will work for page1.php
as the reletive paths are correct. For subsection/page2.php
this will fail as the paths should be ../css/style.css
and ../functions/classes.php
but remain as they are defined in header.php
.
My question is how can I get header.php to always use the correct relative file paths for its includes regardless of where the file calling header.php
(eg apage.php
) is located in the web site directory.
Set a base path to the css /functions :
define('CSS_BASE','insert/full/path/here');
then access css in header.php using
<link rel="stylesheet" href="<?=CSS_BASE;?>/style.css">
When I did this I set a variable (say $urlStart
) at the start of each page ( page1.php
, page2.php
) that contained the relative path of the main directory (eg page1.php
would have $urlStart='./'
, page2.php
would have $urlStart='../'
). Then in your header.php
, use this variable at the start of each URL. Like this:
<link rel="stylesheet" href="<?php echo $urlStart;?>css/style.css">
<?php require_once($urlStart . "functions/classes.php"); ?>
For php includes, making the path relative to header.php is ok.
For the css file, you should use an absolute path, like <link rel="stylesheet" href="/css/style.css">
.
Edit : The css/javascripts files are not "include" ; those are html tags, so they will be processed client-side by the browser. That's the reason why the path should be relative to the url of the page where the html will be, not to its place on the server.
If you are including page2.php inside the page1 then your path will work. no need to go back to the previous folder.
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.