PHP - Split website into files

I am currently developing a website with the aim of exploring a few more, but I just couldn't figure it out and I don't know what to look for exactly, I didn't find anything.

So, basically I have a navigation bar, a content box, and a footer. I would like to split the site into three files. This way, for example, I would only have to edit one file to edit all links in the navigation bar on all pages.

I can just do this by putting:

<?php include('navigation.php'); ?>

Where I want. But here's my problem: on every page I have, my navbar needs to change the active page / tab and highlight it.

My navigation bar looks like this: Home | News | About | Contact

When I click News

and land on the news page, it should be highlighted in the navigation bar (via CSS). But how can I achieve this when I have a navigation bar in one file? Then it will highlight it on ALL pages. This is the problem I am currently having and I don't know if this is possible in PHP?

Any help is appreciated! Thanks to

+3


source to share


3 answers


Easiest method: set a global variable to say "where" and check the nav menu:

eg.

index.php:



<?php
$PAGE = 'home';
include('navigation.php');

      

navigation.php:

<?php

...
if (isset($PAGE) && ($PAGE == 'home')) {
    .... output "home" link with you-are-here highlight
} else {
    ... output regular home link.
}

      

+3


source


Maybe you can check what the current url is and add the active class to your menu items accordingly.

<?php
    $url = basename($_SERVER['PHP_SELF']);    
?>

      

and then when you create the menu links, something like this:



<li class='<?php echo ($url == "about.php") ? "active" : ""?>' >About</li>

      

Something like that.

+3


source


Get the page from the URL descriptor p

. Check if he is allowed, otherwise go home.

Then check if this page is active in the menu if it is; add class active

.

<?php
// Get the page from the url, example: index.php?p=contact
$page = $_GET['p'];

// Whitelist pages for safe including
$whitelist = array('home', 'news', 'about', 'contact');

// Page not found in whitelist
if (!in_array($page, $whitelist)):
    $page = 'home';
endif;

include('header.php');
include('navigation.php');
include($page . '.php'); // Include page according to url
include('footer.php');
?>


<ul>
    <li>
        <a href="index.php?p=home" class="<?php if ($page === 'home'): ?>active<?php endif; ?>">
            Home
        </a>
    </li>
    <li>
        <a href="index.php?p=news" class="<?php if ($page === 'news'): ?>active<?php endif; ?>">
            News
        </a>
    </li>
    <li>
        <a href="index.php?p=about" class="<?php if ($page === 'about'): ?>active<?php endif; ?>">
            About
        </a>
    </li>
    <li>
        <a href="index.php?p=contact" class="<?php if ($page === 'contact'): ?>active<?php endif; ?>">
            Contact
        </a>
    </li>
</ul>

      

0


source







All Articles