简体   繁体   中英

how to create page 404 error in custom PHP MVC?

In my custom PHP MVC, how can I redirect the error page to page404 in .htaccesss? For example, example.com/controller/method , when controller or method not exist, it has to redirect to page404 but I don't know how to do it.

In .htaccess script, I've used ErrorDocument 404 /page404.php page404 is in root and inside of it I put example.com/index/page404 , but it does not work. How do I fix this?

you can where you had analyzed the format of the route, check if this method in that controller exists or not, if there is no method or controller, redirect that to your 404 pages.

an example for controller:

if (file_exists($controller . '.php')) {
   // Controller does exist
} else {
   header("Location: {path_of_views}/404.php");
}

an example for method:

if (method_exists($controller, $methodName)) {
   // Method does exist
} else {
    header("Location: {path_of_views}/404.php");
}

UPDATE:

add ErrorDocument to your .htaccess:

ErrorDocument 404 http://www.example.com/error.html

you can read more in thislink .

You can do it using a routing code in PHP. If you want to do it with the .htaccess anyway, you should check the apache configuration first and set it to "Allowoverride All" on the Directory to authorize .htaccess files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM