OK, so for the first time I am building a full website and working with php. Now I encounter a problem:
Let'ss say my site is simply has a header with a menu and a area with content. Of course, I would like to have a header.php and several content files like content1.php content2.php and content3.php for example. This way you only have to change the menu in 1 file as you would understand.
How then is it best to build the site:
A. put something like this in every content file:
<?php include 'header.php'; ?>
here the content of the content page 1
B. make an index file with something like:
<?php include 'header.php'; ?>
<?php include 'content1.php'; ?>
how then is it done that when in the menu the link to content2.php is clicked the header is still on that page too?
C. something else? Maybe a good tutorial on how to make these kind of pages?
If you're looking to maximize the benefit of reusing code/elements, then you're on the right track with your second option:
B. make an index file with something like:
<?php include 'header.php'; ?>
<?php include 'content1.php'; ?>
how then is it done that when in the menu the link to content2.php is clicked the header is still on that page too?
Here's how (a simplistic example):
Route all of the similar requests (content1,2,3) through your index.php script using the query string - mod_rewrite can make this pretty. Then serve the main content section based on the request.
For example a link:
<a href='index.php?page=content1'>Content 1</a>
And detecting the content to serve:
<php
$pages['content1'] = 'content1.php';
$pages['content2'] = 'content2.php';
$pages['default'] = $pages['content1']; //set default content
$page = 'default';
if(isset($pages[$_GET['page']]){
$page = $pages[$_GET['page']]; //make sure the filename is clean
}
?>
<?php include 'header.php'; //header here?>
<?php include $page; //correct content here?>
Not only is there a single place to change your header, but now there's a single place to change your entire layout.
Of course this is just a simplistic example, there are many PHP frameworks that do all this for you (using MVC).
Simple instead of a index.php including the content files, you do:
header.php:
<a href="content1.php">content 1</a><br />
<a href="content2.php">content 2</a><br />
content2.php:
<?php
include('header.php');
?>
This is the page with 'content 1'
content2.php:
<?php
include('header.php');
?>
This is the page with 'content 2'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With