Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple PHP question about menu & content best practice

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?

like image 228
Javaaaa Avatar asked Dec 07 '25 06:12

Javaaaa


2 Answers

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).

like image 125
Tim Lytle Avatar answered Dec 09 '25 20:12

Tim Lytle


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'
like image 24
Marc B Avatar answered Dec 09 '25 19:12

Marc B