cebo
cebo

Reputation: 818

What are the PHP exit status codes?

From the docs for the exit() function:

Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.

I had thought these were http status codes and had been using them as such (I was confused why my exit(400) call was returning an empty string).

The docs only explicitly mention 0 and 255 as having special meaning and I can't seem to find any documentation anywhere describing what the other 254 codes are meant to be or if they're reserved or anything like that. I also can't really figure out why it would even use a different status code system from http in the first place.

Also, since this isn't https status codes. What is the best way to send those? Should I just echo a number? Put the number as the 'message' in exit ie. exit('400')? Should I even use http status codes at all vs just sending boolean or flags or the like in my responses?

Upvotes: 2

Views: 5827

Answers (3)

Quentin
Quentin

Reputation: 943100

Exit codes are used for command line programming. They have no significance when writing PHP to be invoked by a web server.

Exit code meanings aren't standardised. Generally you would select arbitrary ones and document them so that scripts calling your program could handle them appropriately.

The simplest example of their use is for the shell script idiom for "Do something, then do something else if it is successful".

./uploadFile.php myFile.txt && ./annouceSuccessfulFileUpload.php

If ./uploadFile.php myFile.txt has a non-zero exit code, the second part won't run.

As opposed to "Do something, then do something else regardless":

./uploadFile.php myFile.txt; ./annouceHopefullySuccessfulFileUpload.php

The http_response_code function is used for setting HTTP response codes:

<?php
    http_response_code(400);
?>

Upvotes: 5

axiac
axiac

Reputation: 72177

An exit status code is a code that a program that exits returns to the program that started it. Exit codes are useful in shell scripts (and not only there) but they are not used in the web programming.

Use the PHP function header() to produce an HTTP status code.

Upvotes: 1

Marwane Ezzaze
Marwane Ezzaze

Reputation: 1057

What its saying in the docs is that exit status are from 0-255, but only 0-254 are usable since the last one is reserved. if you wanna set the http response code, perhaps this function might be of use : https://www.php.net/manual/en/function.http-response-code.php

Upvotes: 0

Related Questions