Understandin PHP 404 redirection related to invalid get request

半世苍凉 提交于 2019-12-11 07:58:17

问题


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.


回答1:


.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.




回答2:


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');
}


来源:https://stackoverflow.com/questions/12663519/understandin-php-404-redirection-related-to-invalid-get-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!