Evaluate PHP 404 redirect associated with bad receive request

Ok, I am using traditional php, no frameworks, nothing, I am using a simple procedural way, now my question is that I have been looking for a while, but I am not getting an answer to my question, I am not using .htaccess files like now, but do I really need to understand how the 404 error works? I have a site where I am displaying a post related to a category like category = php so I am passing this as a get request

$_GET['category'] == 'php';

      

Now I am doing 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 to be a valid request value, the rest I want to redirect to 404, but I don’t understand how to do that, so I did so what if I have more than 50 categories? I cannot list them all in this if condition, Inshort how to determine if a given query value is invalid or not.

Any help would be much appreciated.

+1


source to share


2 answers


.htaccess is the way to do it.

ErrorDocument 404 index.php?404

      

this line will tell apache which file to load. The above example calls the main index.php script.

add something like this at the top of your index.php file:

$error_404 = isset($_GET["404"]) ? true : false;

      

now you can tell if there is 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);

      



the best thing to do is 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 ask a question, add it to the appropriate 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.

+1


source


You can 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 can do is create an html / php file for each category and do it like this

if (is_file('sites/' . $popcategory . '.php')
{
    include('sites/' . $popcategory . '.php');
}
else
{
    header('Location:404.php');
}

      

0


source







All Articles