开发者

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

This question already has answers here: Set Response Status Code [duplicate] 开发者_Go百科 (6 answers) Closed 6 years ago.

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

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


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

When to send HTTP status code?

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

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


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

<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>


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.


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):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜