How to avoid repeating the html code? [duplicate]

3

Good evening, folks. This is the following, I'm using the bootstrap and I would like to know how I avoid repeating the same codes in all pages, since the header and footer are the same, this would make the code more readable, I searched and saw that it should be used the Include of PHP, but I do not know how to use it, help me, please. Thankful;)

    
asked by anonymous 19.12.2016 / 01:35

3 answers

5

The first thing to do is to separate your website into 3 files.

  • header.html
  • conteudo.php
  • footer.html

As you can see in the header it will have the header and footer the footer.

So in conteudo.php you will make the includes, header.html at the beginning of the code and footer.html at the end, following example:

<?php include 'header.html'; ?>

<h1>Nome da pagina</h1>

<?php  include 'footer.html'; ?>

And so for all pages you want to reuse the header and footer.

obs. The files that will be included do not necessarily need to be PHP, only where you want to include PHP is necessary.

    
19.12.2016 / 12:28
2

Just save the header and footer in files separated by ex header.php and footer.php

After that in your main page instead of the header and footer you make an include

<?php include("header.php"); ?>

Does the same thing in place of footer

<?php include("footer.php"); ?>
    
19.12.2016 / 01:42
1

You can save to different files. This leaves the code cleaner, readable and faster in case of later issues, of course if used correctly. A good example is if all the pages have the same footer and you need to change information that is present in it, without separating the files you would have to edit in all, giving more work. Here is an example of an index, fragmented into several files:

 <!DOCTYPE html>
<?php 
include("inclusoes/cabecalho.php");
if(isset($_GET['sair']) && $_GET['sair']== true){
    unset($_SESSION['usuario']);
    }
 ?>
<body>
<header id="header"><!--header-->
<?php include_once("inclusoes/menu.php");?>
</header>
<!--/header-->
<?php
if(!isset($categoria)|| $categoria==""){
 include_once("inclusoes/inicio.php");
}
else if(isset($categoria) && $categoria!=""){
    if(file_exists("inclusoes/$categoria.php")){
     include_once("inclusoes/$categoria.php");
    }
    else{
         include_once("404.php");   
        }
    }
 ?>
<?php include_once("inclusoes/rodape.php");?>
</body>
</html>

I hope this helps you to understand. Remember that include_once is guaranteed that the file will not be included again if it has already been added before.

    
19.12.2016 / 02:09