40

I have a php function which adds bad IP's to a MySQL table.

Each page on my site then checks the table and throws a HTTP 401 header if a match is found.

if(badCrawler()){
    header("HTTP/1.1 401 Unauthorized");
    header("Location: error401.php");
}

Is it possible to do this without changing the url?

Thanks

adlr0
  • 758
  • 9
  • 13
Jms Bnd
  • 1,213
  • 3
  • 13
  • 18

2 Answers2

80

Sure. Just exit after your 401 header. No need for the header("Location...") at all.

if(badCrawler()){
    header("HTTP/1.1 401 Unauthorized");
    exit;
}

Side note: 401 typically is used in conjunction with an authentication request.

From the specs:

The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource.

It might be better to use 403 Forbidden to deny access, or even 404 Not Found if you want the bad crawler to think the page doesn't exist any longer:

header("HTTP/1.0 404 Not Found");
exit;

Sending content

Note that your 404 response might result in a blank page in some browsers, see the top answer in this thread for a full explanation of why that is happening. Basically the header is working but it's just up to you to display any HTML content).

The solutions is simple, echo your content (or include a separate file) right before the exit statement.

Community
  • 1
  • 1
jszobody
  • 28,495
  • 6
  • 61
  • 72
  • 1
    Thanks, I changed it to 404 Not Found but the page does not show the error page, it just terminates at the exit. – Jms Bnd Apr 09 '13 at 23:29
  • Use `header("HTTP/1.0 404 Not Found")` and it'll send that header. You may not get an "error" per se, but if you examine the headers on your page you'll see a 404. I updated my answer, with a related thread that provides further details. – jszobody Apr 09 '13 at 23:50
14

Aware this is a little old, but it popped up on a google search of "php, 401s".

Is the issue here that when the page redirects to error401.php that page will return a 200 OK, as error401.php loaded fine. If you really want the 401 page to show, how about this?

if(badCrawler()){
     header("HTTP/1.1 401 Unauthorized");
     include("error401.php");
     exit;
}
Simon Cooke
  • 141
  • 1
  • 2