0

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?

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

Maybe using relative paths for the include in the other index.php file.

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

Comments

1

You are using the server's actual filesystem path to refer to your stylesheets. That's like trying to do something like:

<link href="C:\your_website_path/includes/shop.css"...

and wont work.

I would recommend to change that to something like:

define('ROOT_PATH', 'http://www.your-website-url.com/');

Regards,

Comments

0

what you need to do is make the include for your config absolute, not relative. you begin the path with a dot ./config which means its relative. instead set up your header to include the config file with an absolute path like this

<?php include '/home/user/config.php';?>

This way, any page can find the file no matter its location in the directory structure.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.