1

I want to create a PHP script that allows me to redirect a user into a 404 page (designed by me) to tell him that the url request by him does not exist. Currently I am working offline, so my server folder is www/myproject/pages.php and if a user typed localhost/myproject/files.php per example, I want to take him into a 404 error page.

I know I should use something like header('HTTP/1.1 404 Not Found'); but I don't know how to make the condition:

if(url does not exist in my working folder).

I've tried this script:

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

from this link but still can't know how to add the condition

Community
  • 1
  • 1
Lara Ch
  • 165
  • 3
  • 12
  • 2
    Your link refer to a total different question (how to check if an **external** url does not exist). You have to modify .htaccess (or apache config) to redirect 404 on your site. See [here](http://stackoverflow.com/questions/19962787/rewrite-url-after-redirecting-404-error-htaccess) – fusion3k Apr 23 '16 at 08:46
  • Thanks that was really helpfull – Lara Ch Apr 26 '16 at 13:03

1 Answers1

3

You can do routing in PHP as well. Something like https://github.com/nikic/FastRoute if you want. Any undefined routes(pages) can be pushed to a 404 page.

Alternatively use your .htaccess or nginx config to redirect pages that don't exist.

nginx

error_page 404 /index.html;

apache

ErrorDocument 404 /custom_404.html

htaccess

ErrorDocument 404 http://example.com/404/
RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]
NotJeeves
  • 43
  • 2
  • I can't find .htacess in my wamp server folder – Lara Ch Apr 26 '16 at 13:03
  • You can create one if it isn't there. There's a few tutorials on doing this an enabling it. – Fabor Apr 26 '16 at 13:16
  • @LaraCh: How are you checking for .htaccess ? It is hidden sometimes. Like when you access it by non root user on cpanel or using any tool like winSCP. Make sure you can see the hidden files. – Vaibs Feb 05 '17 at 20:34