Page 1 of 1
Creating 404
Posted: Tue Feb 09, 2010 12:30 pm
by daebat
I would like to add a 404 page to my website. Is it possible with this code setup?
Code: Select all
<div id="links">
<?php
switch($_GET['page'])
{
case "1": include('page1.php');
break;
case "2": include('page2.php');
break;
case "3": include('page3.php');
break;
case "4": include('page4.php');
break;
default: include('home.php');
}
?>
</div>
Re: Creating 404
Posted: Tue Feb 09, 2010 12:44 pm
by AbraCadaver
Sure, but you'll probably need the default to be 404. Something like this:
Code: Select all
if(!isset($_GET['page'])) {
$page = "0";
} else {
$page = $_GET['page'];
}
switch($page) {
case "0": include('home.php');
break;
case "1": include('page1.php');
break;
case "2": include('page2.php');
break;
case "3": include('page3.php');
break;
case "4": include('page4.php');
break;
default: include('404.php');
}
Re: Creating 404
Posted: Tue Feb 09, 2010 1:45 pm
by daebat
Awesome! Thanks!
Re: Creating 404
Posted: Mon Jun 11, 2012 12:44 pm
by kirashi
You could also try this code for your site:
.htaccess file
Code: Select all
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^([0-9a-zA-Z_-]+)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ /$1
</IfModule>
This will rewrite pages people visit into a variable that PHP can get whilst loading a page. The purpose is to let you develop a dynamic site, whilst keeping the links nice and pretty for the user. EXAMPLE:
http://yoursite.com/welcome will give a page=welcome that PHP can then use.
index.php file
Code: Select all
<?php
if (!empty($_GET['page'])) {
$page = $_GET['page'];
} else {
$page='home';
}
?>
This goes at the TOP of your index.php file, before anything else. It loads in the variable or sets the default if there isn't one. In this example, the default is 'home' because we have setup a 'home.php' file in our /includes folder.
index.php content section
Code: Select all
<div id="content">
<?php
switch ($page) {
case $page:
$page = str_replace("/", "", $page);
if (file_exists("includes/".$page.".php")) {
include "includes/".$page.".php";
break;
} else {
include "includes/404.php";
break;
}
?>
</div>
This goes in between your content section; our example already includes div content tags. It will read in the $page variable, and check to see if a file exists in the /includes folder. If it does, load 'er up! If it doesn't, 404 Error not found. Simple as that. This way you don't even have to add each page manually to your index.php file, as it just checks to see if they exist.