如何在不同文件夹中为每个页面包含一个标题

How can I use one header.php file for every html page in different folders?

For example:

My header.php file is in homepage/includes folder.

And i include like this include "includes/header.php";

up to now, everything is okay.

And i have a diffent folder on my homepage called "users"

And i wanna include my header.php file, which is on homepage/includes folder, on homepage/users/index.php file.

And i include like this "include "../includes/header.php", but I have errors.

Cause on my header.php file I call my css files like <link href="assets/css/demo.css"/>

So I need to copy my header.php file to users folder.

And I need to change href="assets/...." like href="../assets/...."

Isn't there any way to solve it?? Thank you.

append the line to all php files which require the header

Note: please use the correct path in file_location/header.php

<?php
include_once('header.php');
?>

First of the wall, you can create config.php file with global variables to all of your php files which needs that variables. Put it in the main folder of your project and include it in any file you need.

Then, you can define $path = '/absolute/path/to/your/project'; variable in your config.php and use it when you need. Then, if you ever will need to change this path value, you only should change value of that variable.

At the other hand, it is an magic constant __DIR__ (http://php.net/manual/en/language.constants.predefined.php), which return absolute path to file with it (if you use this constant in includes/header.php it will return /path/to/homepage/includes/, but if you use it in users/index.php it will return /path/to/homepage/users/).

In this case it should work, when you type include __DIR__.'../includes/header.php';, but I recommend to solve your problem in the first way, because if structure of your project will be changed, you must change any file with those lines in it.

The problem you are facing is relative vs absolute paths.

When using require_once you can use a constant defined in your index.php or inside a config.php or setup.php depending on your application. It would look something like:

require_once APP_PATH . 'includes/header.php';

In your case APP_PATH could be defined as the full path before the include, ie. define('APP_PATH', dirname(__FILE__) . '/'); or if you want to hardcode it define('APP_PATH', '/home/www/my-app/');

You can use the absolute path to your css files for the assets to work,

<link href="/assets/css/demo.css"/>

OR for better portability you can create a little function to wrap all style calls:

<link href="<?php echo css_asset('demo.css'); ?>"/>

// Then the possible definition of css could be
function css_asset($style)
{
    return '/assets/css/' . $style;
}