Ok, am using traditional php, no frameworks, nothing, I am using simple procedural way, now my question is I was searching for a while but am not getting an answer to my question, I am not using .htaccess files as of now, but I really need to understand how 404 error works? I am having a website, where I show post's related to category, say category=php, so I pass this as a get request
$_GET['category'] == 'php';
Now currently what am doing is something like this :
$pocategory = $_GET['category'];
if($pocategory == 'php' || $pocategory == 'javascript') {
//Then show related posts
} else {
header('Location:404.php');
exit;
}
I mean I just want php and javascript as valid request's value, rest I want to redirect to 404 but am not understanding how to do it so I did this way, what if am having more than 50 categories? I cant list them all in this if condition, Inshort how to detect whether the given get request value is invalid or not..
Any help will be much appreciated.
.htaccess is the way to do this.
ErrorDocument 404 index.php?404
that line will tell apache what file to load. The example above calls the main index.php script.
add something like this to the top of your index.php file:
$error_404 = isset($_GET["404"]) ? true : false;
now you can detect if you have a 404 error request. $error_404 will be true, so why not add a simple function:
function error_404($error_404)
{
if($error_404 == true)
{
// do some error stuff here, like set headers, and some text to tell your visitor
}
}
now just call your function:
error_404($error_404);
best to do that immidiatley after the get handler:
error_404($error_404)
$error_404 = isset($_GET["404"]) ? true : false;
or combine the two into one line:
error_404($error_404 = isset($_GET["404"]) ? true : false);
to address the question, add this to the relevant script:
$pocategorys_ar = array("php","javascript");
if (!in_array($pocategory, $pocategorys_ar))
{
error_404(true);
}
Make sure it has access to the error_404() function.
You could put all categories inside an array like this:
$pocategories = array
(
'php',
'javascript'
);
if (in_array($pocategory, $pages))
{
// ...
}
else
{
header('Location:404.php');
}
Another thing you could do is creating a html/php file for every category and do it like so
if (is_file('sites/' . $popcategory . '.php')
{
include('sites/' . $popcategory . '.php');
}
else
{
header('Location:404.php');
}