Códigos de resposta HTTP

A classe Inphinit\Http\Status fornece uma lista de constantes para códigos de status de resposta HTTP comuns:

Respostas informativas

Constante Código Descrição
Status::HTTP_CONTINUE 100 Essa resposta provisória indica que o cliente deve continuar a solicitação ou ignorar a resposta caso a solicitação já tenha sido concluída.
Status::HTTP_SWITCHING_PROTOCOLS 101 Este código é enviado em resposta a um cabeçalho de solicitação de Upgrade do cliente e indica o protocolo para o qual o servidor está mudando.
Status::HTTP_PROCESSING 102 Este código era usado em contextos WebDAV para indicar que uma solicitação havia sido recebida pelo servidor, mas nenhum status estava disponível no momento da resposta.
Status::HTTP_EARLY_HINTS 103 Este código de status destina-se principalmente a ser usado com o cabeçalho Link, permitindo que o agente do usuário inicie o pré-carregamento de recursos enquanto o servidor prepara uma resposta ou se conecta previamente a uma origem da qual a página precisará de recursos.

Respostas bem-sucedidas

Constante Código Descrição
Status::HTTP_OK 200 A solicitação foi bem-sucedida.
Status::HTTP_CREATED 201 A solicitação foi bem-sucedida e um novo recurso foi criado como resultado. Essa é normalmente a resposta enviada após solicitações POST ou algumas solicitações PUT.
Status::HTTP_ACCEPTED 202 A solicitação foi recebida, mas ainda não foi processada. Ela não representa um compromisso, visto que não há como o HTTP enviar posteriormente uma resposta assíncrona indicando o resultado da solicitação. É destinada a casos em que outro processo ou servidor lida com a solicitação, ou para processamento em lote.
Status::HTTP_NON_AUTHORITATIVE_INFORMATION 203 Este código de resposta significa que os metadados retornados não são exatamente os mesmos que os disponíveis no servidor de origem, mas foram coletados de uma cópia local ou de terceiros. Isso é usado principalmente para espelhos ou backups de outro recurso. Exceto nesse caso específico, a resposta 200 OK é preferível a este status.
Status::HTTP_NO_CONTENT 204 Não há conteúdo para enviar nesta solicitação, mas os cabeçalhos são úteis. O agente do usuário pode atualizar seus cabeçalhos em cache para este recurso com os novos cabeçalhos.
Status::HTTP_RESET_CONTENT 205 Indica ao agente do usuário para redefinir o documento que enviou esta solicitação.
Status::HTTP_PARTIAL_CONTENT 206 Este código de resposta é usado em resposta a uma solicitação de intervalo quando o cliente solicitou uma ou mais partes de um recurso.
Status::HTTP_MULTI_STATUS 207 Transmite informações sobre múltiplos recursos, para situações em que múltiplos códigos de status podem ser apropriados (WebDAV).
Status::HTTP_ALREADY_REPORTED 208 Usado dentro de um elemento de resposta para evitar a enumeração repetida dos membros internos de múltiplas associações à mesma coleção (WebDAV).
Status::HTTP_IM_USED 226 O servidor atendeu a uma solicitação GET para o recurso e a resposta é uma representação do resultado de uma ou mais manipulações de instância aplicadas à instância atual (codificação HTTP Delta).

Mensagens de redirecionamento

Constante Código Descrição
Status::HTTP_MULTIPLE_CHOICES 300 Na negociação de conteúdo orientada por agentes, a solicitação possui mais de uma resposta possível e o agente do usuário ou o usuário deve escolher uma delas. Não existe uma maneira padronizada para os clientes escolherem automaticamente uma das respostas, portanto, esse método é raramente utilizado.
Status::HTTP_MOVED_PERMANENTLY 301 O URL do recurso solicitado foi alterado permanentemente. O novo URL é fornecido na resposta.
Status::HTTP_FOUND 302 This response code means that the URI of requested resource has been changed temporarily. Further changes in the URI might be made in the future, so the same URI should be used by the client in future requests.
Status::HTTP_SEE_OTHER 303 The server sent this response to direct the client to get the requested resource at another URI with a GET request.
Status::HTTP_NOT_MODIFIED 304 This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.
Status::HTTP_USE_PROXY 305 Defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.
Status::HTTP_RESERVED 306 This response code is no longer used; but is reserved. It was used in a previous version of the HTTP/1.1 specification.
Status::HTTP_TEMPORARY_REDIRECT 307 The server sends this response to direct the client to get the requested resource at another URI with the same method that was used in the prior request. This has the same semantics as the 302 Found response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the redirected request.
Status::HTTP_PERMANENT_REDIRECT 308 This means that the resource is now permanently located at another URI, specified by the Location response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.

Client error responses

Constant Code Description
Status::HTTP_BAD_REQUEST 400 The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
Status::HTTP_UNAUTHORIZED 401 Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response.
Status::HTTP_PAYMENT_REQUIRED 402 The initial purpose of this code was for digital payment systems, however this status code is rarely used and no standard convention exists.
Status::HTTP_FORBIDDEN 403 The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike 401 Unauthorized, the client's identity is known to the server.
Status::HTTP_NOT_FOUND 404 The server cannot find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web.
Status::HTTP_METHOD_NOT_ALLOWED 405 The request method is known by the server but is not supported by the target resource. For example, an API may not allow DELETE on a resource, or the TRACE method entirely.
Status::HTTP_NOT_ACCEPTABLE 406 This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent.
Status::HTTP_PROXY_AUTHENTICATION_REQUIRED 407 This is similar to 401 Unauthorized but authentication is needed to be done by a proxy.
Status::HTTP_REQUEST_TIMEOUT 408 This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers use HTTP pre-connection mechanisms to speed up browsing. Some servers may shut down a connection without sending this message.
Status::HTTP_CONFLICT 409 This response is sent when a request conflicts with the current state of the server. In WebDAV remote web authoring, 409 responses are errors sent to the client so that a user might be able to resolve a conflict and resubmit the request.
Status::HTTP_GONE 410 This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code.
Status::HTTP_LENGTH_REQUIRED 411 Server rejected the request because the Content-Length header field is not defined and the server requires it.
Status::HTTP_PRECONDITION_FAILED 412 In conditional requests, the client has indicated preconditions in its headers which the server does not meet.
Status::HTTP_CONTENT_TOO_LARGE 413 The request body is larger than limits defined by server. The server might close the connection or return a Retry-After header field.
Status::HTTP_URI_TOO_LONG 414 The URI requested by the client is longer than the server is willing to interpret.
Status::HTTP_UNSUPPORTED_MEDIA_TYPE 415 The media format of the requested data is not supported by the server, so the server is rejecting the request.
Status::HTTP_RANGE_NOT_SATISFIABLE 416 The ranges specified by the Range header field in the request cannot be fulfilled. It's possible that the range is outside the size of the target resource's data.
Status::HTTP_EXPECTATION_FAILED 417 This response code means the expectation indicated by the Expect request header field cannot be met by the server.
Status::HTTP_IM_A_TEAPOT 418 The server refuses the attempt to brew coffee with a teapot.
Status::HTTP_MISDIRECTED_REQUEST 421 The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
Status::HTTP_UNPROCESSABLE_CONTENT 422 The request was well-formed but was unable to be followed due to semantic errors (WebDAV).
Status::HTTP_LOCKED 423 The resource that is being accessed is locked (WebDAV).
Status::HTTP_FAILED_DEPENDENCY 424 The request failed due to failure of a previous request (WebDAV).
Status::HTTP_TOO_EARLY 425 Indicates that the server is unwilling to risk processing a request that might be replayed (Experimental).
Status::HTTP_UPGRADE_REQUIRED 426 The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an Upgrade header in a 426 response to indicate the required protocol(s).
Status::HTTP_PRECONDITION_REQUIRED 428 O servidor de origem exige que a solicitação seja condicional. Essa resposta visa evitar o problema de "atualização perdida", em que um cliente solicita o estado de um recurso via GET, modifica-o e o envia de volta ao servidor via PUT, enquanto, nesse ínterim, um terceiro já modificou o estado no servidor, causando um conflito.
Status::HTTP_TOO_MANY_REQUESTS 429 O usuário enviou muitas solicitações em um determinado período de tempo (limitação de taxa).
Status::HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE 431 O servidor não está disposto a processar a solicitação porque os campos do cabeçalho são muito grandes. A solicitação pode ser reenviada após a redução do tamanho dos campos do cabeçalho.
Status::HTTP_UNAVAILABLE_FOR_LEGAL_REASONS 451 O agente do usuário solicitou um recurso que não pode ser fornecido legalmente, como uma página da web censurada pelo governo.

Respostas de erro do servidor

Constante Código Descrição
Status::HTTP_INTERNAL_SERVER_ERROR 500 O servidor encontrou uma situação que não sabe como resolver. Este erro é genérico, indicando que o servidor não consegue encontrar um código de status 5XX mais apropriado para responder.
Status::HTTP_NOT_IMPLEMENTED 501 O método de requisição não é suportado pelo servidor e não pode ser processado. Os únicos métodos que os servidores são obrigados a suportar (e, portanto, que não devem retornar este código) são GET e HEAD.
Status::HTTP_BAD_GATEWAY 502 Essa resposta de erro significa que o servidor, ao funcionar como um intermediário para obter uma resposta necessária para processar a solicitação, recebeu uma resposta inválida.
Status::HTTP_SERVICE_UNAVAILABLE 503 O servidor não está pronto para processar a solicitação. As causas comuns são um servidor em manutenção ou sobrecarregado. Observe que, juntamente com esta resposta, deve ser enviada uma página explicativa explicando o problema. Esta resposta deve ser usada para condições temporárias e o cabeçalho HTTP Retry-After deve, se possível, conter o tempo estimado para a recuperação do serviço. O administrador do site também deve atentar para os cabeçalhos relacionados ao cache enviados com esta resposta, pois essas respostas para condições temporárias geralmente não devem ser armazenadas em cache.
Status::HTTP_GATEWAY_TIMEOUT 504 Essa mensagem de erro é exibida quando o servidor está atuando como um gateway e não consegue obter uma resposta a tempo.
Status::HTTP_VERSION_NOT_SUPPORTED 505 A versão HTTP usada na solicitação não é suportada pelo servidor.
Status::HTTP_VARIANT_ALSO_NEGOTIATES 506 O servidor apresenta um erro de configuração interna: durante a negociação de conteúdo, a variante escolhida está configurada para realizar a negociação de conteúdo por conta própria, o que resulta em referências circulares na criação de respostas.
Status::HTTP_INSUFFICIENT_STORAGE 507 O método não pôde ser executado no recurso porque o servidor não consegue armazenar a representação necessária para concluir a solicitação com sucesso (WebDAV).
Status::HTTP_LOOP_DETECTED 508 O servidor detectou um loop infinito durante o processamento da solicitação (WebDAV).
Status::HTTP_NOT_EXTENDED 510 A solicitação do cliente declara uma extensão HTTP (RFC 2774) que deveria ser usada para processar a solicitação, mas a extensão não é suportada.
Status::HTTP_NETWORK_AUTHENTICATION_REQUIRED 511 Indica que o cliente precisa se autenticar para obter acesso à rede.
Página inicial
Apoie com uma estrela no GitHub