-1

I wanted to know if there is a way to simulate a 404 error in PHP. For example, I have this URL: www.mydomain.com/user/[Username] which redirects to /profile.php?user=[username]. I want the server to show my 404 Error page if the username is not registered.

[PHP] Here it is some sample code:

<?
   if (notRegistered($_GET['user'])) {
        // Throw 404 Error
   }
?>

Thanks in advance.

Joaquín O
  • 1,431
  • 1
  • 9
  • 16

1 Answers1

5

HTTP reports the status code via the headers. Use the header() function in PHP to set the status code:

if (notRegistered($_GET['user'])) {
     header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
     exit(1);
}

Also you may want to send an error page to the browser:

if (notRegistered($_GET['user'])) {
     header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
     readfile('path/to/error404.html');
     exit(1);
}

$_SERVER\['SERVER_PROTOCOL'\] will contain HTTP/1.0 or HTTP/1.1.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Doesn't work for me.. – Joaquín O Dec 13 '13 at 20:44
  • What does `Doesn't work` mean? – hek2mgl Dec 13 '13 at 20:46
  • I've tried the first option, and nothing seemed to happen.. So, you mean that I have to include my 404 error page manually? – Joaquín O Dec 13 '13 at 20:54
  • yes, exactly... The easiest thing for testing would be: `echo 'Not found';`.. You may prepare candy 404.html's afterwards. ;) – hek2mgl Dec 13 '13 at 20:55
  • So there is no way to show the browser's 404 page?? – Joaquín O Dec 13 '13 at 20:57
  • 1
    "browser's" 404 page is always coming from server. You misunderstood that – hek2mgl Dec 13 '13 at 20:58
  • What I mean is: if the server sends a 404 error header, why doesn't the browser show a 404 error? – Joaquín O Dec 13 '13 at 20:59
  • The browser just shows what the server sends. That's the same for success pages as for error pages. Only if a server isn't available the browser shows a custom error page. (That's because the server is just not reachable and can't sed an error page) – hek2mgl Dec 13 '13 at 21:01
  • Oh, I thought that if the server sends '404 error', the browser would show it's 404 error page.. Knowing this, why is it useful for me to send the '404 header'? – Joaquín O Dec 13 '13 at 21:03
  • You need to understand [HTTP](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) and it's [status codes](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) – hek2mgl Dec 13 '13 at 21:05
  • Nevermind.. I'll just include the error page.. Thanks. – Joaquín O Dec 13 '13 at 21:09
  • One last question: if I use `header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');` and then `var_dump(headers_list());` I can't see the header I just set.. Is it OK? – Joaquín O Dec 13 '13 at 21:15
  • have you used echo before? or other output? – hek2mgl Dec 13 '13 at 21:20
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/43152/discussion-between-joaquin-o-and-hek2mgl) – Joaquín O Dec 13 '13 at 21:26