You are currently browsing the page Inclusion in the PHP category.

Inclusion

This will simplify your life. Let's see the structure of a webpage once again:

<!--CHOOSE A DOCTYPE TO VALIDATE-->
<html>
<head>
<title>your page title</title>
</head>
<body>
// LAYOUT HEADER
// CONTENTS
// LAYOUT FOOTER
</body>
</html>

We'll want to separate the content from everything else: layout, header, footer. First, the header.

<!--CHOOSE A DOCTYPE TO VALIDATE-->
<html>
<head>
<title>your page title</title>
</head>
<body>
// LAYOUT HEADER

Save it as header.php and we will now extract the footer:

// LAYOUT FOOTER
</body>
</html>

Save it as footer.php and we're almost done! We're missing an index.php page and the contents:

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

Save it as index.php! Each time the page index.php is loaded, it will "call" the files header.php and footer.php! You only need to add your contents codes between the two include codes. Nothing else. No html, head or body tag since everything is already in header.php and footer.php!

That's nice but how do you make other pages? It's the same:

<? include("header.php"); ?>
// OTHER CONTENTS HERE!
<? include("footer.php"); ?>

And save as anything.php! :)

Download: PHP Inclusion sample files  PHP Inclusion sample files (1.1 KB, 218 hits)

Print This Post Print This Post



Sponsors


3 Responses to “Inclusion”

I have a question... What about directories? Say I have footer.php, top.php and menu.php in the root directory, but I have some files in the /articles directory. Do I have to link to the inclusion files with ../ from the files in that directory, or is there another way?

The problem would be that I'd need to write the entire url (http://...) to all the links in the menu, for any images and so on, that is within the inclusion files. Or is it simply best to have all the files in the same directory? Which would create a lot of chaos...

Thanks for your time =)

Trine


Hi Trine, in your menu.php, I recommend you using this link structure:

<a href="/index.php">main page</a>
<a href="/subpage/page.php">sub page</a>

etc. Instead of rewriting all the URLs, start the link with a slash (that brings you to your site root) then put your folder path. This way, you won't have to rewrite them :)


I got my php to work but i can't go to any subpages. I link to let's say subpage/page.php and then the page has no css no header and no footer but it works with pages that aren't in any folder.


Leave a Comment

Works? Doesn't work? Other tips? Please leave a comment! :)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

To post codes, please go to SimpleCode and transform your codes first, so that it will displayed properly. Indeed, < and > need to be converted to &lt; and &gt; :)


Close
E-mail It