Reputation: 163
I am new to php and understand that this is quite a common problem. I have read a lot of related issues over the net and here at stack overflow however I have not been able to successfully implement them.
I have a project with a directory structure like so:
Project/
includes/
header.php
footer.php
sidebar.php
css/
style.css
index.php
blog/
index.php
Within the index.php in the root I pull in the includes like so:
include 'includes/header.php';
And the css file in the header.php like so:
<link rel="stylesheet" href="css/style.css">
Now this works on the index.php file in the root and any other file placed within the root. However it breaks for all pages within a sub folder for example the blog/index.php
My main question is how can i properly reference my css files and my includes in a project so that the files are accessible to second level pages as well?
Notes:
- I am working on a local server
- All project files are contained within a PROJECT folder in the root - (localhost:8888/Project/index.php)
Any help will be much appreciated.
Thank you.
Upvotes: 1
Views: 4981
Reputation: 1849
The simple way but not best way is that you can always link to absolute path :(i do not recommend)
<link rel="stylesheet" href="http://localhost/Project/css/style.css">
It's better to have config file that has a base_url variable and always link your css and other stuff through base_url;
Upvotes: 0
Reputation: 5781
You need to reference it via the root of your application. use the following options
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="//domain.com/css/style.css">
include $_SERVER['DOCUMENT_ROOT'].'/includes/header.php';
The way you currently have it is not going to work for any files outside of the root of your domain name. What it is doing is the following.
You are at http://example.com/ and your site is including css/style.css so it is appending to the domain. At the root level this is fine. now if you are at http://example.com/myFile/andFolder it is still appending to the domain if you do not include the leading slash... So now it is looking for your style at http://example.com/myFile/andFolder/css/style.css. Adding the leading slash is telling the server, I want to look for this in the root of my domain.
The second option I have for the <link rel....
with the two //
before the domain name is just a quick way to host it via https:// if that is what the current page is located at.
Upvotes: 1