Skip to content
Advertisement

require footer and header each page but error 500

Hi,

I start in PHP and I create my website. I create a component of header and footer to print on each page with : require '/assets/components/header.php'; and require '/assets/components/footer.php';

So, the problem is that on localhost, it works, but on website, it didn’t work and i have a http error 500

Repertory : Folder tree

I try :

1. The different type of link

require 'assets/components/header.php';

require './assets/components/header.php';

require '../assets/components/header.php';


2. create a variable $BASE_URL to stock the url of the website and require like this : require "$BASE_URL/assets/components/header.php";. I set the setting ‘allow_url_include’ to true but i have this error :

JavaScript

‘#####’ -> my website

I read in a topic, that not secure to set ‘allow_url_include’ to true so if we can do different.

Header.php

JavaScript

Advertisement

Answer

When including component files in PHP, you should be using file paths, not URLs. For example, we can use relative file paths to include the header in pageOther1.php, which should be like this.

JavaScript

To make things more efficient, especially if you are going to include multiple components and have different levels of nested views, you could define the header and footer paths (and include any other global scripts like functions.php) in a PHP file (e.g. initialize.php or config.php) on the root directory of your app. That way you only need to require initialize.php and include the components you want using PHP constants.

Here’s a more efficient approach

Define the component paths as a constant in a PHP file (e.g. initialize.php) on the root directory

JavaScript

Then include the components and scripts in a view. An example with pageOther1.php will be:

JavaScript

You can easily extend this for multiple components and function scripts.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement