Forum

PHP Header('HTTP/1.1 401 Unauthorized') returns 200

12 December 2014, 21:32
Hiawatha version: 9.8
Operating System: Debian

Hi Hugo,
When I access an folder with a .htaccess file, and fail to authenticate, I nicely get a return header with 401
Request Method:GET
Status Code:401 Unauthorized

HTTP/1.1 401 Unauthorized
Date: Fri, 12 Dec 2014 20:11:08 GMT
Server: Hiawatha v9.8
Accept-Ranges: bytes
Connection: keep-alive
WWW-Authenticate: Basic realm="Hallo"
Content-Length: 677
Content-Type: text/html


But when I create a php file with:
<?php
header('WWW-Authenticate: Basic realm="401 Test"');
header('HTTP/1.1 401 Unauthorized');
?>

Then I get the response with 200, but I expected 401:
Request Method:GET
Status Code:200 OK
Request Headersview parsed
GET /401.php HTTP/1.1

Response Headersview source
Connection:keep-alive
Content-Encoding:gzip
Content-type:text/html
Date:Fri, 12 Dec 2014 20:16:48 GMT
Server:Hiawatha v9.8
Transfer-Encoding:chunked
Vary:Accept-Encoding
WWW-Authenticate:Basic realm="401 Test"


I do not have any ErrorHandler specified in my hiawatha.conf.

I want to create RESTFUL api's and catch the return value with (for now) basic authentication. So In javascript I want to catch a 401:
...
if (http_request.readyState === 4 && http_request.status === 401) {
...


Although my 401.php page is found correctly, so 200, I would expect a 401, because my header does mention that.

Thanks,


PS: I will upgrade to 9.9
12 December 2014, 21:47
Version 9.9 returns the same results.
Hugo Leisink
12 December 2014, 21:49
Instead of
header('HTTP/1.1 401 Unauthorized');

try this:
header('Status: 401');
12 December 2014, 22:34
That indeed does give me the authentication popup. And after pressing Cancel I get a 401.
The php specifications [php.net] tell me to sent a RAW http header [www.faqs.org]]

[4 HTTP Message

4.1 Message Types

HTTP messages consist of requests from client to server and responses
from server to client.

HTTP-message = Request | Response ; HTTP/1.1 messages
]

So why does Hiawatha requires different header (in php)?
Hugo Leisink
14 December 2014, 18:50
The RFC2616 mentions the HTTP protocol. What you are talking about is the CGI protocol. That's different.

Some webservers prefer the 'HTTP/1.x <code>' line, others prefer the Status line. Hiawatha is one of those last.
14 December 2014, 22:10
Ok, to workaround this issue and create a generic result (in this case for php), I was able to work around it:
header('WWW-Authenticate: Basic realm="401 Test"');
//header('HTTP/1.1 401 Unauthorized'); //Hiawatha 200
//header('HTTP/1.1 401 Unauthorized',false, 401); //Hiawatha 200
//header('Status: 401'); //Hiawatha 401
http_response_code(401); //Hiawatha 401
?>

So I will use http_response_code now to be compatible between web servers (Still prefer Hiawatha above other web servers )
Thanks.
This topic has been closed.