Search code examples
phpinclude-path

PHP include paths within directories


I have looked around at a few different questions about the same sort of problem I'm having. I have took a solution and adapted it to my own project.

Here is my directory structure.

/css
    -style.css
/includes
    -shop.css
    -header.php
    -footer.php
/php
/js
/shop
    -index.php

-index.php <-- homepage
-config.php  

Inside my config.php I have

define('ROOT_PATH',$_SERVER['DOCUMENT_ROOT']);

My header.php

<?php include './config.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <?php echo '<link href="'.ROOT_PATH.'/css/style.css" rel="stylesheet">';?>
  <?php if ($_SERVER['REQUEST_URI'] == '/shop/'){echo '<link href="'.ROOT_PATH.'/includes/shop.css" rel="stylesheet">';} ?>
</head>

The only problem is, for any other page other than the root index.php file, the path for the config.php file becomes incorrect. Thus the CSS paths then become incorrect as ROOT_PATH isn't defined anywhere.

What would be the best way to handle paths when using includes?


Solution

  • Use $_SERVER['HTTP_HOST'].$_SERVER['DOCUMENT_ROOT'] gets the document root for eg var/com/images. $_SERVER['HTTP_HOST'] will get current url like http://example.com/images.TYour code should look like this

    define('ROOT_PATH',$_SERVER['HTTP_HOST']);
    

    And include this way

    <?php include'../config.php';
    

    Hope this helps you