I have an MVC structure in my php.
I use autoload to initialize the correct controller.
Here is a very dumbed down version of my index.php:
<?php
spl_autoload_extensions('.class.php');
spl_autoload_register();
$controller = strtolower($_GET["controller"]);
$action = strtolower($_GET["action"]);
$obj = new $controller();
$obj->{$action}();
So let's say the user loads www.example.com/Page/View
. Apache will rewrite it to www.example.com?controller=Page&action=View
. Then when php calls $obj = new $controller();
, it will try to find page.class.php
in the same directory as the file (obviously in my application the file structure isn't so trivial, with namespaces, etc...), and then load the Page
class inside and execute Page->View();
.
Now, say the user makes a typo and tries to load www.example.com/Pagr/View
. Ideally, he should get a 404 header response. But with the current implementation, php will just throw a Fatal error
when it fails to autoload pagr.class.php
.
How can I prevent this error from happening? I've done some research, and I can't figure out a way to check if the class can be autoloaded or not prior to the new
call.