用php创建html页眉

问题描述:

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?

首先,我是网络开发的新手,请原谅我,如果这是一个愚蠢或重复的问题。 p >

我的所有网页都有相同的标题,所以我只需将以下行添加到每个页面的顶部: p>

 &lt;?php require(  'header.html')?&gt; 
  code>  pre> 
 
 

这很好用。 但现在我想改变标题中的图像,具体取决于它所在的页面。 我正在考虑使用这样的php函数: p>

  function create_header($ image){
 // 1。 回显header.html的内容
 
 // 2。 用$ image替换默认图像位置如果不为空
} 
  code>  pre> 
 
 

问题是我不知道如何执行步骤1或2.这是否可行和/ 或者有更好的方法来做我想做的事吗? p> div>

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.

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);
    }
?>