search
HomeBackend DevelopmentPHP TutorialExplain HTTP status codes (2xx, 3xx, 4xx, 5xx). Give examples.

HTTP status codes are divided into four categories: 2xx means the request is successful, 3xx means redirection is required, 4xx means client error, and 5xx means server error. 2xx status code such as 200 OK means the request is successful, 201 Created means the resource creation is successful; 3xx status code such as 301 Moved Permanently means permanent redirection, 302 Found means temporary redirection; 4xx status code such as 404 Not Found means the resource is not found, 400 Bad Request means the request syntax error; 5xx status code such as 500 Internal Server Error means the server internal error, 503 Service Unavailable means the server cannot process the request temporarily.

Explain HTTP status codes (2xx, 3xx, 4xx, 5xx). Give examples.

introduction

Exploring the mystery of HTTP status codes is a fun and practical journey. We will have an in-depth understanding of the four major categories of status codes, 2xx, 3xx, 4xx and 5xx. Each category represents different responses in network requests. This article will not only help you understand the basic definition and use of these status codes, but will also let you see their performance in actual applications through specific examples. Whether you are a beginner front-end or a senior back-end developer, you can draw useful knowledge from it.

Review of basic knowledge

The HTTP status code is a three-digit code returned by the server in response to an HTTP request, which tells the client the result of the processing of the request. These codes are part of the HTTP protocol to help developers and users understand the state of network communication. Understanding HTTP status code is crucial for debugging and optimizing network applications.

Core concept or function analysis

2xx success status code

The 2xx status code indicates that the request has been successfully received, understood, and accepted by the server. The most common one is 200 OK, which means that the request is successful and the response body contains the requested data.

 HTTP/1.1 200 OK
Content-Type: text/html

<!DOCTYPE html>
<html>
<head>
<title>Example Domain</title>
</head>
<body>
<h1 id="Example-Domain">Example Domain</h1>
<p>This domain is for use in illustrative examples in documents.</p>
</body>
</html>

Another example is 201 Created. When a resource is successfully created, the server returns this status code.

 HTTP/1.1 201 Created
Location: /new-resource
Content-Type: application/json

{
  "id": "123",
  "name": "New Resource"
}

The advantage of 2xx status codes is that they explicitly indicate that the request is successful, which is very important for the client. It is worth noting, however, that 200 OK does not always mean that the content is up to date or complete, which can lead to some misunderstandings.

3xx redirect status code

The 3xx status code indicates that the request needs further processing to complete. The most common are 301 Moved Permanently and 302 Found, which are used to redirect requests to a new URL.

 HTTP/1.1 301 Moved Permanently
Location: https://new-domain.com

301 means that the resource has been moved permanently, while 302 means temporary redirection. When using 3xx status code, it should be noted that the client must be able to handle redirects correctly, otherwise the request may fail.

4xx client error status code

The 4xx status code indicates that there is an error in the client's request. The most common one is 404 Not Found, which means the requested resource is not found on the server.

 HTTP/1.1 404 Not Found
Content-Type: text/html

<!DOCTYPE html>
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1 id="Not-Found">Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body>
</html>

Another common one is 400 Bad Request, which means that the request cannot be understood by the server due to syntax errors.

 HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": "Invalid request syntax"
}

Use of 4xx status codes requires caution because they directly affect the user experience. Especially the 404 error, if handled improperly, may lead to user churn.

5xx Server Error Status Code

The 5xx status code indicates that an error occurred during the server processing the request. The most common one is 500 Internal Server Error, which means that the server encounters an unexpected situation and cannot complete the request.

 HTTP/1.1 500 Internal Server Error
Content-Type: text/html

<!DOCTYPE html>
<html>
<head>
<title>500 Internal Server Error</title>
</head>
<body>
<h1 id="Internal-Server-Error">Internal Server Error</h1>
<p>An unexpected condition was encountered.</p>
</body>
</html>

Another example is 503 Service Unavailable, which means that the server cannot process the request for the time being.

 HTTP/1.1 503 Service Unavailable
Retry-After: 3600
Content-Type: text/html

<!DOCTYPE html>
<html>
<head>
<title>503 Service Unavailable</title>
</head>
<body>
<h1 id="Service-Unavailable">Service Unavailable</h1>
<p>The server is temporarily unable to service your request due to maintain downtime or capacity issues.</p>
</body>
</html>

The processing of 5xx status codes requires special attention because they directly affect the availability and user experience of the service. It is crucial to ensure proper error handling and logging.

Example of usage

Basic usage

In practical applications, the use of HTTP status codes is very common. For example, when you visit a website, the browser decides how to handle the response based on the status code returned by the server. If it is 200 OK, the browser will display the page content; if it is 404 Not Found, the browser will display an error page.

Advanced Usage

In API design, the use of HTTP status codes is more complicated. For example, you can use 201 Created to indicate that the resource is created successfully and include the Location field in the response header to point to the URL of the new resource. At the same time, 409 Conflict can be used to represent resource conflicts, prompting the client to handle the conflict before trying again.

Common Errors and Debugging Tips

Common errors during development include 404 Not Found and 500 Internal Server Error. For 404 errors, you can debug by checking whether the URL is correct or if there is any problem with the server configuration. For 500 errors, you need to check the server log, find out the specific cause of the error, and fix it.

Performance optimization and best practices

There are a few points to note when using HTTP status code:

  • Performance optimization : For 3xx redirect status codes, try to minimize the number of redirects, because each redirect will increase the request time.
  • Best practice : In API design, the rational use of HTTP status codes can improve the readability and maintainability of the API. For example, using 204 No Content to indicate that the request is successful but no content is returned, instead of using 200 OK and returning an empty response body.

Through these practices and understandings, you can not only better use HTTP status codes, but also optimize your network applications and improve user experience.

The above is the detailed content of Explain HTTP status codes (2xx, 3xx, 4xx, 5xx). Give examples.. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor