Redirect to custom error page if there is error in the page

Anonymous picture Anonymous · May 31, 2014 · Viewed 18.5k times · Source

I am new to PHP web development. I want to know is there any code in PHP that redirects me to a page(let's name it "myerrorpage.php") if there is some error on the page?

In JSP it's possible using the following code

<%@ page errorPage="myerrorpage.jsp" %>

I want to know is there any above JSP type of code in PHP?is yes then please help

Any help is appreciated...

Answer

Vasile Goian picture Vasile Goian · May 31, 2014

In php you don't redirect when there is an error in the code, you simply catch that error and then you take whatever actions you consider necessary.

In order to catch the errors in the code, you must define a custom error handler, using set_error_handler.

Also you can handle the uncaught exceptions using set_exception_handler.

The following code will redirect to yourerrorpage.php when there is an error on the PHP code.

<?php
function error_found(){
  header("Location: yourerrorpage.php");
}
set_error_handler('error_found');
?>

Please note that the header("Location: page.php"); redirect type doesn't work after the content output begins.


Alternatively, you might want to try Apache custom error responses