-1

everytime I create a website I usually end up by creating a simple index.php file that will load the requested pages.

Example:

include ('header.php');
if(isset($_GET['page']))
{
    $page = $_GET['page'];
    $display = $page.'.php';
}
else
{
     include ('homepage.php');
}
include ('footer.php'); ?>

THE PROBLEM: If I want to create a connection.php file that will access my database usally it won't work in other pages beacuse I have to rewrite "include('connection.php')", in every single file that isn't the index.php.

THE REQUEST: How can I embed header, footer, connection, etc... In a proper and safe way ? So I don't have to include it in every other file ?

How do you usually include the header and the footer in every page, in order to create a dynamic website ?

B001ᛦ
  • 2,036
  • 6
  • 23
  • 31
HelloThere
  • 13
  • 3
  • 7
    Possible duplicate of [Creating a PHP header/footer](https://stackoverflow.com/questions/8054638/creating-a-php-header-footer) – Sfili_81 Nov 21 '18 at 14:02

1 Answers1

0

There's multiple ways to fix this.

  1. Use a templating engine, like Blade or Twig.
  2. Create an autoloader

Blade will allow you to make a layout, which can look like this:

<html>
    <head>
        <title>App Name - @yield('title')</title>
        @yield('css')
    </head>
    <body>
        <!-- Include all your files -->
        @php
          include('myfile.php');
        @endphp

        <div class="container">
            @yield('content')
        </div>

        @yield('js')
    </body>
</html>

Then for every other page you can create a blade file that extends the layout.

@extends('layout.file')

@section('title', 'Page Title')

@section('content')
    <p>This content will be placed in the container in the layout.</p>
@endsection

You can write an auto-loader by yourself or use a pre-written one. I'm not going to attempt writing one because I usually go with the pre-written ones.

This should give you an idea though.

rpm192
  • 2,630
  • 3
  • 20
  • 38
  • Thanks, you definitely solved my problem, I will look for autoloaders tutorials now :) – HelloThere Nov 21 '18 at 14:13
  • No problem. If you're writing big sites I definitely recommend a framework such as Laravel (Uses Blade) or Symfony (Uses twig). If the answer solved your issue, please consider accepting it as it could help others that face similar issues. You can do this after 15 minutes. – rpm192 Nov 21 '18 at 14:15
  • I will look into it ! By the way thanks for helping me :) – HelloThere Nov 21 '18 at 14:20
  • Laravel is really simple to use, it'll really take a lot of work away! – rpm192 Nov 21 '18 at 14:20