在没有重定向的情况下使用 php 抛出 401 标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15914130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:11:18  来源:igfitidea点击:

Throwing a 401 header with php without redirect

phphttpheader

提问by Jms Bnd

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

我有一个 php 函数,可以将错误的 IP 添加到 MySQL 表中。

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

然后,我网站上的每个页面都会检查表格,如果找到匹配项,则会抛出一个 HTTP 401 标头。

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

Is it possible to do this without changing the url?

是否可以在不更改 url 的情况下执行此操作?

Thanks

谢谢

回答by jszobody

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

当然。就exit在您的 401 标头之后。header("Location...")根本不需要。

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

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

旁注:401 通常与身份验证请求结合使用。

From the specs:

规格

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

响应必须包含一个 WWW-Authenticate 头域(第 14.47 节),其中包含适用于所请求资源的质询。

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

使用403 Forbidden拒绝访问可能会更好,或者即使404 Not Found您希望错误的爬虫认为该页面不再存在:

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 threadfor 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).

请注意,您的 404 响应可能会导致在某些浏览器中出现空白页面,请参阅此线程中的最佳答案以获取有关为什么会发生这种情况的完整说明。基本上标题正在工作,但您可以显示任何 HTML 内容)。

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

解决方案很简单,在exit语句之前回显您的内容(或包含一个单独的文件)。

回答by Simon Cooke

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

意识到这有点旧,但它在谷歌搜索“php,401s”时弹出。

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

这里的问题是,当页面重定向到 error401.php 时,该页面将返回 200 OK,因为 error401.php 加载正常。如果你真的想要显示 401 页面,这个怎么样?

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