Reputation: 1903
I have an ajax application which returns content of article with given id. All requests are sent to a php file, which takes article content from database and echos it.
Now, there is problem: php file will always have 200 OK
status. And I want it to send some status code, which says that article doesn't exists. Something completely out of usual range (like 100 000
or similar).
My question is, is it possible to set some status like that with php?
Upvotes: 1
Views: 706
Reputation: 109
Generally you can mix two ways of answering in PHP. Best practice is to send correct http status code , but with correct code (like 404 for not found and 409 for wrong input (just example)) you can send text response message like if it is standard answer.
So you can mix previous answers (if you need it):
http_response_code(404);
$response = array(
'status' => 100001,
'result' => 'Document was not found on server'
);
echo json_encode($response);
exit;
But i'm not sure you need sub-statuses in that situation.
With that in your javascript you can operate by xhr response code to determine the error itself and show to user some text and substatus that came from server in response body;
Upvotes: 1
Reputation: 227270
You can set the HTTP status code with http_response_code
. You can only use status codes in the 1xx, 2xx, 3xx, 4xx, or 5xx ranges. You can't make up your own status codes. See this answer for info on that: https://stackoverflow.com/a/11871377
For a status of "article doesn't exist", you can simply use 404 Not Found
.
http_response_code(404);
Here is a list of HTTP status codes: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
EDIT: http_response_code
only works on PHP 5.4+. If you don't have PHP 5.4 you can do:
header("HTTP/1.0 404 Not Found", TRUE, 404);
More info on this: https://stackoverflow.com/a/12018482
Upvotes: 3
Reputation: 49
You could send a 404 status code back using http_response_code.
Another option would be to encode a status code and the data you want to return as a JSON response and return that to the browser.
$response = array(
'status' => 100001,
'result' => '<h1>Title...'
);
echo json_encode($response);
exit;
Upvotes: 2