0

Firstly I'm very new to web development so forgive me if this is a stupid or repeated question.

All my web pages have the same header so I simply add the following line to the top of every page:

    <?php require('header.html') ?>

This works fine. But now I'd like to vary the image in the header depending on which page it is on. I'm thinking about using a php function like this:

    function create_header($image){
        //1. echo contents of header.html

        //2. replace default image location with $image if not null
    }

Problem is I don't know how to do steps 1 or 2. Is this possible and/or is there a better way of doing what I want?

2 Answers 2

1

You should use some basic form of templating.

Let's say your header looks like this:

<div id="header">
    <img src="images/myimage.jpg" alt="" />
    <h1>Welcome to my site!</h1>
</div>

If we modify it to turn the image into a variable we get this:

<div id="header">
    <img src="images/<?php echo $header_image; ?>" alt="" />
    <h1>Welcome to my site!</h1>
</div>

Now all you have to do is set your variable before you include your header file like so:

<?php
$header_image = "image2.jpg";
include "header.html";
?>

This concept of basic templating can be applied to an entire page template and is not limited to header files.

Sign up to request clarification or add additional context in comments.

2 Comments

What would be the best way of using a default image with this method?
There are a few ways you can set a default with this method. If you have a config file that you include throughout the site you can add the default there. Just make sure if you are overriding the default that you do it after you have included the config. The second method would be to use an if statement inside the header file and check to see if your variable has been set and if not set it to your default image.
1

You could always use a PHP page for your header, and pass it whatever image you wanted through GET.

header.php

<?php
    if (isset($_GET['img']))
        echo '<img src="' . $_GET['img'] . '">'; //The brackets allow for complex variables in double quoted strings
    else
        echo '<img src="default_header.png">'
?>

page.php

<?php
    function create_header($image) {
       require('header.php?img=' . $image);
    }
?>

1 Comment

Just leave out the function create_header($image) {.... and only use the require('header.php?img=' . $image); since all his pages have headers. A function is not needed and would be extra code. e.g. require('header.php?img=index'); would load the index header image, etc..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.