'Basic PHP CMS help needed. If the page isn't available, it should show a error page instead

Okay, so I have this 10+ year old PHP code I cobbled together to make a basic PHP driven site. It works and I'm using it in production now. But I have a problem that I can't figure out the solution to!

Here is my index.php code, this is probably all that is relevant.

<?php
require("./config.php");
$okfiles = array("main","page1","some-other-page","anotherexample");
if ($_GET["p"] AND @in_array( $_GET["p"] , $okfiles ) ) {
    $includeFile = $_GET["p"] .".php";
    if (@file_exists($includeFile)){
        include($includeFile);
    }
}
else {
    include("./main.php");
}
?> 

So, user goes to website.tld, and index.php is served. What is shown on the index page is the content of main.php on the webserver. If they navigate to website.tld/page1, they then see the content of page1.php within the basic little templating system I have. That is what I want. Some Nginx re-write rules make it look nice and all is good there.

The issue I am having is if someone goes to website.tld/a-page-that-doesnt-exist, instead of seeing the web-server's default 404 page, instead, they just see the content of main.php as if they had went to the website's index instead of a page that should trigger an error. HOWEVER, if they got to website.tld/a-page-that-doesn-exist.php (or any other page/request that has a file extension associated with it... They see the error page.

How can I make it that if the page being requested isn't defined in $okfiles = array that it then triggers a normal error page?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source