PHP Manual
Working with files

Include (folding pages from pieces)

23. 08. 2019

Obsah článku

PHP is originally a templating language, which was created to make it easy to put pieces of pages together.

Supported formats

Folding works as text, so it is advisable to use relevant formats such as .html or .md.

When a PHP file is pasted, its contents are executed as if they physically existed at the pasted location.

Folding pages and inserting common content

Often we need to create several pages that have common content - for example, a menu.

In plain HTML, we would first create a page with a menu and then copy it many times. But in PHP we can automate the whole process.

Let's have a file menu.html where the menu content is and index.php where we put the content and the menu.

A simple example:

<div class="page">
<div class="content">
include __DIR__
'/article/' . ($_GET['page'] ?? 'index') . '.html';
<div class="menu">
include 'menu.html';

This script automatically inserts the page content from the /article directory and reads the file name according to the user input (URL parameter ?page=...). If no parameter was passed, index.html is used.

So the URL might look like, for example, and load /article/contacts.html.

Jan Barášek   Více o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Související články

All systems normal.