Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom 404 Error Page in PHP

I am a novice in PHP, I hope you can help me with this problem. How can I create a custom 404 error page in PHP without going anywhere or redirect it to other page.

Ex. mysite.com/no-where

The page no-where does not exists. I want to display a 404 error message with design on that URL.

How can I get the current URL? I got an error on this. Coz I want to check the header if its 404.

$url = $_SERVER['REQUEST_URI'];
$array = get_headers($url);
$string = $array[0];
if(strpos($string,"200")) {
    echo 'url exists';
} else {
    echo 'url does not exist';
}
like image 310
user3745440 Avatar asked Dec 20 '22 13:12

user3745440


2 Answers

Create a .htaccess file and put the following line in it:

ErrorDocument 404 /errorpageFileName.php 

That will set the page 'errorpageFileName.php to your error 404 page. You can of course change the file name to your likings.

You can read more in-depth about it here: Custom 404 error issues with Apache

like image 75
TrickyInt Avatar answered Dec 28 '22 06:12

TrickyInt


It's really important to have a correct 404 error page, because:

  • It helps your site / webapp visitors to guide for the correct place in your site
  • Much better SEO
  • It's just looks better

In additional the the answers here, I would suggest you to have different messages for different error types. For example, define in your .htacess file an error page for different failure types:

ErrorDocument 500 /500.html
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html

More information about custom 404 error pages.

like image 42
Johnny Avatar answered Dec 28 '22 05:12

Johnny