Search code examples
phpheaderhead

How to send data to a previously included PHP file?


I have a header.php and a footer.php file. My HTML header is in header.php and I have an index.php file.

I’m using so (index.php):

require 'header.php';

$example_code = 'example';

︙

require 'footer.php';

And my header.php:

<html>
 <head>
  <title>
     ???
  <title>
  <meta name="description" content="???" /> 
   <meta name="keywords" content="???" /> 
 </head>
<body>
︙

I want to send some data from index.php to header.php to print it there (see the ???). I’m thinking of the header() function but I can’t see any example in the PHP manual.


Solution

  • The best thing you could do is separating logic from presentation. Using an MVC approach, where you take care of all logic in one file, and then display the outcome of what you've done in a presentation only layer.

    Besides that, if you want to keep your approach, what you simply have to do is to make assignments before header.php is included. So, suppose you want to change your page title, this is what you need to do:

    index.php

    <?php
    $title = 'My Page Title';
    $description = 'My meta description';
    $keywords = 'keyword list';
    include('header.php');
    
    ?>
    

    header.php

    <html>
     <head>
      <title>
         <?php echo $title; ?>
      <title>
      <meta name="description" content="<?php echo $description; ?>" /> 
       <meta name="keywords" content="<?php echo $keywords; ?>" /> 
     </head>
    <body>
    

    It's as simple as that. Just keep in mind you can't make assignments to a page/script, AFTER such has been included

    Again, though, I'm trying to answer you, not necessarily suggesting this approach. If your application has just a couple of pages, that's ok. If it's bigger (or going to be), something like the MVC pattern (two-step view pattern) is a better alternative IMHO.