Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php include file from another directory

Tags:

include

php

Here is a structure example:

/main
 /css
  style.css
 /include
  article1.php
  article2.php
 header.php
 index.php

In my header.php I have the following code for the css:

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

And, for example, in my index.php I have the following as the first line:

<?php include 'header.php'; ?>

Now, everything works fine as it is. Next I'm going to insert the following code in the article1.php file:

<?php include '../header.php'; ?>

The contents (menus and other html) are displayed correctly, however the CSS won't be displayed/recognized at all. Basically what's happening is that the header file is being included but the server isn't respecting the directory parenting. For the CSS to be displayed correctly I'd have to change the link rel for the CSS to ../css/style.css, but if I do so it won't work on files located in the main directory.

I hope I made my problem clear. What am I doing wrong? How can I include files from different directories and preserve the links inside them?

like image 963
coldpumpkin Avatar asked Mar 28 '13 13:03

coldpumpkin


4 Answers

In your site's <head> section, insert a <base> element with the href attribute. Set the href attribute to the base URL of your website, and all relative requests will be sent through that base URL.

<base href="http://my-website-url.com/" />
<link rel="stylesheet" type="text/css" href="css/style.css" />

With a correctly-set base tag, the user's browser will attempt to load your stylesheet from the URL http://my-website-url.com/css/style.css.

Note: this not only affects stylesheets, but all relative links in the document.

like image 154
Matt Avatar answered Oct 21 '22 17:10

Matt


It has to do with how pathing works in includes. I recommend pathing things from the doc root whenever possible.

<?php include( $_SERVER['DOCUMENT_ROOT'] . '/header.php' ); ?>

That will work in any of your files.

like image 38
mikevoermans Avatar answered Oct 21 '22 15:10

mikevoermans


Instead of using relative paths:

href="css/style.css"

use absolute paths from the webroot:

href="/css/style.css"
like image 31
bubba Avatar answered Oct 21 '22 16:10

bubba


You should include your css file from the root. So /css/style.css so way it will always start at the root and then go down from there. I believe that should fix your problem in all cases.

like image 36
wallerjake Avatar answered Oct 21 '22 17:10

wallerjake