Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing a 401 header with php without redirect

Tags:

http

php

header

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

like image 896
Jms Bnd Avatar asked Apr 09 '13 23:04

Jms Bnd


People also ask

What does Unauthenticated status code 401 mean?

The 401 Unauthorized Error is an HTTP status code error that represented the request sent by the client to the server that lacks valid authentication credentials. It may be represented as 401 Unauthorized, Authorization required, HTTP error 401- Unauthorized. It represents that the request could not be authenticated.

Why 401 Unauthorized?

The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.

What is 401 authorization required?

A 401 Authorization Required error means you can try accessing the resource again using the correct credentials. In other words, it's often a temporary problem, unlike an HTTP 403 error in which you're expressly forbidden to access the page you're hoping to reach.


2 Answers

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.

like image 75
jszobody Avatar answered Oct 06 '22 18:10

jszobody


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; } 
like image 32
Simon Cooke Avatar answered Oct 06 '22 18:10

Simon Cooke