File-based engine in PHP

We will implement a site engine that will allow us to create a template file, to which, depending on the URL, different content will be connected.

Let the structure of our page look like this:

layout.php<!DOCTYPE html>
<html>
  <head>
    <title>title</title>
  </head>
  <body>
    <header>
      header
    </header>
    <main>
      content
    </main>
    <header>
      footer
    </header>
  </body>
</html>

Let's insert some command we invented for inserting content at the place where the content insertion should happen, for example like this: {{ content }}. Let's change our site template:

layout.php<!DOCTYPE html>
<html>
  <head>
    <title>title</title>
  </head>
  <body>
    <header>
      header
    </header>
    <main>
      {{ content }}
    </main>
    <header>
      footer
    </header>
  </body>
</html>

Now let's create a folder view, where we will place content files. Directly in this folder or in subfolders.

The first file will be like this:

view/page1.php<div>
  content 1
</div>

The second file will be like this:

view/dir/page2.php<div>
  content 2
</div>

The third file will be like this:

view/dir/sub/page3.php<div>
  content 3
</div>

Now let's make it so that the corresponding file is pulled from the view folder based on the URL from the address bar. In our case, for the URL /page1 it will be the first file, for the URL /dir/page2 - the second, and for the URL /dir/sub/page3 - the third.

Let's start the implementation. First, in the file .htaccess, let's make sure all requested addresses, except for resource files, redirect to the page index.php:

.htaccessRewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !\.(js|css|ico|jpg|png|gif)$
RewriteRule .+ index.php

On the page index.php, let's get the requested URL into a variable:

index.php<?php
  $url = $_SERVER['REQUEST_URI'];
?>

Then get the text of the template file:

index.php<?php
  $layout = file_get_contents('layout.php');
?>

Now, based on the URL, get the corresponding content file from the view folder:

index.php<?php
  $content = file_get_contents('view' . $url . '.php');
?>

Replace the command we invented in the template text with the content obtained from the file:

index.php<?php
  $layout = str_replace('{{ content }}', $content, $layout);
?>

Output the template file with the substituted content to the browser:

index.php<?php
  echo $layout;
?>

Let's put it all together and get the following code:

index.php<?php
  $url = $_SERVER['REQUEST_URI'];
  
  $layout  = file_get_contents('layout.php');
  $content = file_get_contents('view' . $url . '.php');
  
  $layout = str_replace('{{ content }}', $content, $layout);
  
  echo $layout;
?>
Задание 1

Implement the described file-based engine.