<?php
// config
include "config.php";
// functions
include "functions.php";
// page router
if(isset($_GET["page"])) {
if(in_array($_GET["page"], PAGES)) {
$page = $_GET["page"];
} else {
redirect("404");
}
} else {
$page = HOME;
}
if($page=="404") {
header("HTTP/1.0 404 Not Found");
}
// titles, meta descriptions
include "meta.php";
// page rendering
include "templates/header.php";
include "pages/$page.php";
include "templates/footer.php";
?>
<?php
// URI
define("URI", "http://example.com/");
// homepage
define("HOME", "home");
// allowed pages
define("PAGES",
array(
"about",
"contact",
"404"
)
);
home, about, contact, 404 - all these are filenames without extension and all of them are placed in the pages folder. For example, pages/home.php, pages/about.php, pages/contact.php, ...
<?php
function redirect($page = HOME) {
if($page==HOME) {
header("Location: ".URI);
} else {
header("Location: ".URI."?page=$page");
}
die();
}
// router
if(isset($_GET["page"])) {
if(in_array($_GET["page"], PAGES)) {
$page = $_GET["page"];
} else {
redirect("404");
}
} else {
$page = HOME;
}
If the variable $_GET["page"]
is set (if(isset($_GET["page"])) {
)
then check if it belongs to one of the allowed pages (if(in_array($_GET["page"], PAGES)) {
).
If the condition is true then accept the page ($page = $_GET["page"]
), if not - then redirect to 404 page (redirect("404")
).
In case if the variable $_GET["page"]
is not set, we set our site to homepage ($page = HOME
).
if($page=="404") {
header("HTTP/1.0 404 Not Found");
}
<?php
$title["home"] = "Homepage";
$title["about"] = "About Us";
$title["contact"] = "Contacts";
$title["404"] = "404 - Page Not Found";
$meta_descr["home"] = "Homepage meta description";
$meta_descr["about"] = "Meta description about us...";
Meta descriptions may not be added for all pages.
// page rendering
include "templates/header.php";
include "pages/$page.php";
include "templates/footer.php";
<title><?php echo $title[$page]; ?></title>
<?php if(isset($meta_descr[$page])) { ?>
<meta name="description" content="<?php echo $meta_descr[$page]; ?>">
<?php } ?>
<link rel="stylesheet" href="<?php echo URI; ?>styles.css">
<ul class="nav col-12 col-lg-auto me-lg-auto mb-2 justify-content-center mb-md-0">
<li><a href="<?php echo URI; ?>" class="nav-link px-2 text-<?php if($page=="home") echo "secondary"; else echo "white"; ?>">Home</a></li>
<li><a href="<?php echo URI; ?>?page=about" class="nav-link px-2 text-<?php if($page=="about") echo "secondary"; else echo "white"; ?>">About</a></li>
<li><a href="<?php echo URI; ?>?page=contact" class="nav-link px-2 text-<?php if($page=="contact") echo "secondary"; else echo "white"; ?>">Contact</a></li>
</ul>
No comments found