简体   繁体   中英

Include html file with image using PHP

I am a newbie in website development.

here is my problem:

I have 2 HTML files. they are 'index.php' and 'header.php'. I try to include 'header.php' in to the 'index.php' using this code:

'index.php'

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

'header.php' contain this code:

<h1>Its header</h1>
<img src="img/006-tumblr.png" width="200" height="200">

its the folder hirearchy:

-index.php
  --header
    --img
       -006-tumblr.png
    -header.php 

When I open 'index.php', 'header.php' is included but the image is not displaying.

So how can I include 'header.php' with the image?

A good way of proceeding would be to have a folder "img" in your root public HTML path containing all images, eventually with subfolders to separate them. The reason for that is that your main controller is launching from root. In that way, wherever you call your image file, you just have to go to img/ in order to find it. The same logic applies to all media. So, if you intend to have video for example, you could have a main folder media with a img subfolder and a vid subfolder. This type of logic has to be defined at start of project so that you don't have to refactor in the middle of it.

Giving location from root directory makes image accessible from any location.

<?php define('WEBSITE_BASE', $_SERVER["SERVER_NAME"]);  ?>

<img src="<?=WEBSITE_BASE?>/header/img/006-tumblr.png" width="200" height="200">

Best linking policy you should always follow to link static assets to your page so that it links wherever the item is used.

The logic of including a file into another is different from linking a CSS file. When you include a PHP file, the entire code is added to the source file and then the server compiles the codes. So the image files and other resources should be addressed relative to the source document (not the included one). This logic is different in a CSS file and the resource files eg a background image is complied relative to the CSS file (Because a CSS may be used in different files hirearchy). So this will work:

<h1>Its header</h1>
<img src="header/img/006-tumblr.png" width="200" height="200"

Footnote: If you want to use header in different files with different hirearchy the solution for the question above is to set BASEURL for your document and setting the resource and anchores relative to the baseurl.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM