如何让 php 页面返回 503 错误(或任何非 200 错误)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2760884/
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 07:35:53  来源:igfitidea点击:

How do I make php page return a 503 error (or anything non-200)

phphttp

提问by benstpierre

A former developer wrote or client-server api in PHP. It simply sends messages as xml using post/response in a very simplistic fashion. The problem is that even when there is an error (ex: invalid arguments passed into the server side) we get a HTTP 200 response with a page like this

前开发人员用 PHP 编写或客户端-服务器 api。它只是以非常简单的方式使用 post/response 将消息作为 xml 发送。问题是,即使出现错误(例如:传递到服务器端的参数无效),我们也会收到 HTTP 200 响应,页面如下

<h4>Unknown error!</h4>

In firebug I can see that the actually HTTP response is a 200. How can we send a different response (ie:503) when we programatically detect in our php code that it is appropriate to do so.

在 firebug 中,我可以看到实际的 HTTP 响应是 200。当我们以编程方式在我们的 php 代码中检测到适合这样做时,我们如何发送不同的响应(即:503)。

回答by ssube

Use PHP's headerfunction to send the code (along with the HTTP version and any other headers you need). More complete info:

使用 PHP 的header函数发送代码(连同 HTTP 版本和您需要的任何其他标头)。更完整的信息:

When to send HTTP status code?

何时发送 HTTP 状态码?

http://php.net/manual/en/function.header.php

http://php.net/manual/en/function.header.php

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 300');//300 seconds

回答by Ben Racicot

I worked on a site that had been hacked and had to use HTACCESS to do this.

我在一个被黑客入侵的网站上工作,不得不使用 HTACCESS 来做到这一点。

<IfModule mod_rewrite.c>

 RewriteEngine on

 # let this (iescaped) IP address see the real site:
 # RewriteCond %{REMOTE_ADDR} !^123.45.67.89

 RewriteCond %{REQUEST_URI} !/maintenance.php$ [NC]

 RewriteCond %{REQUEST_URI} !.(jpe?g?|png|gif|css|js) [NC]

 RewriteRule .* /maintenance.php [R=503,L]

</IfModule>

回答by chelmertz

On top of your script (or really, before any output is sent as a response):

在您的脚本之上(或者实际上,在任何输出作为响应发送之前):

<?php header("HTTP/1.0 404 Not Found");or any other HTTP status code.

<?php header("HTTP/1.0 404 Not Found");或任何其他HTTP 状态代码

回答by Chris

A good class for achieving this can be found here: http://www.krisjordan.com/php-class-for-http-response-status-codes/- use it like this (before any other output):

可以在此处找到实现此目的的好类:http: //www.krisjordan.com/php-class-for-http-response-status-codes/- 像这样使用它(在任何其他输出之前):

<?php header(StatusCodes::httpHeaderFor(503)); ?>