4

On my website users can enter a HTTP status code into a standard text input field. i.e, 200, 400, 404, 403 etc...

Is there any way to check if the HTTP status code is valid. For example if a user enters '123' it will return false. I currently cannot think of or find a way other than doing a large ugly if or switch statement.

3 Answers 3

6

For those using Symfony or Laravel, you can do the following :

use Illuminate\Http\Response;

function is_valid_http_status(int $code) : bool {
    // thanks @James in the comments ^^
    return array_key_exists($code, Response::$statusTexts);
} 

Assuming that Response is one of those:

  • Symfony\Component\HttpFoundation\Response
  • Illuminate\Http\Response
Sign up to request clarification or add additional context in comments.

1 Comment

array_key_exists($code, Response::$statusTexts)
4

According to w3.org the following HTTP/1.1 status codes are valid:

$status_code = array("100","101","200","201","202","203","204","205","206","300","301","302","303","304","305","306","307","400","401","402","403","404","405","406","407","408","409","410","411","412","413","414","415","416","417","500","501","502","503","504","505");

if(in_array("404", $status_code)){
    echo "valid";
  }else{
    echo "invalid";
  }

Comments

1

There are no built-in functions to achieve this in PHP, but a less verbose way for a check than an if or switch statement could be the use of an array:

$validStatusCodes = [200, 201, 202, ...];

if (in_array($submittedStatusCode, $validStatusCodes)) {
    // Ok
} else {
    // Not ok
}

1 Comment

At php.net/manual/en/function.http-response-code.php#107261 you can find a switch with most of the status codes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.