A. Clarke A. Clarke - 4 months ago 11
CSS Question

PHP include function not display images or css

I am testing a small blog site I created using XAMPP. PHP files work with includes when in parent folder, but I have a folder called "2016" inside the same htdocs folder and in that folder I have "1" "2" "3" "4" etc for the months.

In each of these folders I will put blog posts (php files with html includes), but when I do the includes, only the html is loaded, the images nor the css are not.

Below are the includes I have tried:

<?php
$page_title = 'Test Page';



$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/includes/header.html";
include($path);



?>


and also tried

<?php

include ('/../../includes/sidebar.html');

include ('/../../includes/footer.html');

?>


Neither options have worked.

Any help will be greatly appreciated!

Answer

This is because you are using relative path to load your images and css.

Simple solution is to make your relative path to absolute.

You can achieve this like:

1) Use Base Path in html head tag

 <base href="http://localhost/yoursite/"> 

Now you can load images and css in relative way as it knows what is the base path after you define it. Now you can use something like

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

With php

  $base_url = 'http://localhost/yoursite/';

and then

<img src="<?php echo $base_url; ?>/images/image1.png"/>