Chuyển tới nội dung
Home » Http Status Code Php | Sending Http Status Codes With `Header()`

Http Status Code Php | Sending Http Status Codes With `Header()`

PHP http status code 1049 with MySQL

PHP HTTP Response: Main Tips

  • HTTP PHP functions allow you to manipulate PHP HTTP response (the information sent by your browser to server) before outputting it.
  • These functions are inbuilt into PHP core.
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

Why Status Codes Matters For SEO

As the name suggests, SEO is all about catering to search engines, so that users are more likely to come across your site. Search engines actively crawl status codes and will determine how your site is indexed as a result.

For example, if your site has plenty of 404 errors that exist from internal or external, links then this can harm your rankings because this will not generate a helpful experience for users. In a nutshell, search engines are looking out for healthy status codes, as this indicates everything is ticking over as it should be.

PHP http status code 1049 with MySQL
PHP http status code 1049 with MySQL

Hạng mục các HTTP status code

Tất cả các HTTP status code phản hồi được chia ra thành 5 hạng mục riêng biệt và là các số nguyên có 3 chữ số. Chữ số đầu được dùng để xác định loại phản hồi, trong khi 2 chữ số cuối thì không có bất kỳ vai trò phân loại nào. HTTP status code sẽ cho ta biết liệu 1 yêu cầu HTTP cụ thể đã được hoàn thành thành công hay chưa.

Các ứng dụng hiểu HTTP status code không cần phải biết hết tất cả code, tức là dù code không xác định cũng có cụm từ để chỉ lý do không xác định. Cụm từ này không cho phía client nhiều thông tin nhưng các ứng dụng HTTP đó phải hiểu được nó thuộc 1 trong 5 hạng mục riêng biệt. 5 hạng mục đó bao gồm:

– 1xx (100 – 199): Information responses / Phản hồi thông tin – Yêu cầu đã được chấp nhận và quá trình xử lý yêu cầu của bạn đang được tiếp tục.

– 2xx (200 – 299): Successful responses / Phản hồi thành công – Yêu cầu của bạn đã được máy chủ tiếp nhận, hiểu và xử lý thành công.

– 3xx (300 – 399): Redirects / Điều hướng – Phía client cần thực hiện hành động bổ sung để hoàn tất yêu cầu.

– 4xx (400 – 499): Client errors / Lỗi phía client – Yêu cầu không thể hoàn tất hoặc yêu cầu chứa cú pháp không chính xác. 4xx sẽ hiện ra khi có lỗi từ phía client do không đưa ra yêu cầu hợp lệ.

– 5xx (500 – 599): Server errors / Lỗi phía máy chủ – Máy chủ không thể hoàn thành yêu cầu được cho là hợp lệ. Khi 5xx xảy ra, bạn chỉ có thể đợi để bên hệ thống máy chủ xử lý xong.

Other Response Types

The

response

helper may be used to generate other types of response instances. When the

response

helper is called without arguments, an implementation of the

Illuminate\Contracts\Routing\ResponseFactory

contract is returned. This contract provides several helpful methods for generating responses.

View Responses

If you need control over the response’s status and headers but also need to return a view as the response’s content, you should use the

view

method:

return response()->view(‘hello’, $data, 200)->header(‘Content-Type’, $type);

Of course, if you do not need to pass a custom HTTP status code or custom headers, you may use the global

view

helper function.

JSON Responses

The

json

method will automatically set the

Content-Type

header to

application/json

, as well as convert the given array to JSON using the

json_encode

PHP function:

return response()->json([‘name’ => ‘Abigail’,’state’ => ‘CA’,]);

If you would like to create a JSONP response, you may use the

json

method in combination with the

withCallback

method:

return response()->json([‘name’ => ‘Abigail’, ‘state’ => ‘CA’])->withCallback($request->input(‘callback’));

File Downloads

The

download

method may be used to generate a response that forces the user’s browser to download the file at the given path. The

download

method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

return response()->download($pathToFile);return response()->download($pathToFile, $name, $headers);

[!WARNING]

Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII filename.

Streamed Downloads

Sometimes you may wish to turn the string response of a given operation into a downloadable response without having to write the contents of the operation to disk. You may use the

streamDownload

method in this scenario. This method accepts a callback, filename, and an optional array of headers as its arguments:

use App\Services\GitHub;return response()->streamDownload(function () {echo GitHub::api(‘repo’)->contents()->readme(‘laravel’, ‘laravel’)[‘contents’];}, ‘laravel-readme.md’);

File Responses

The

file

method may be used to display a file, such as an image or PDF, directly in the user’s browser instead of initiating a download. This method accepts the absolute path to the file as its first argument and an array of headers as its second argument:

return response()->file($pathToFile);return response()->file($pathToFile, $headers);

Learn HTTP Status Codes In 10 Minutes
Learn HTTP Status Codes In 10 Minutes

Response Macros

If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the

macro

method on the

Response

facade. Typically, you should call this method from the

boot

method of one of your application’s service providers, such as the

App\Providers\AppServiceProvider

service provider:

The

macro

function accepts a name as its first argument and a closure as its second argument. The macro’s closure will be executed when calling the macro name from a

ResponseFactory

implementation or the

response

helper:

return response()->caps(‘foo’);

Common Use Cases for HTTP Status Codes

In this section, we will show you some common use cases for sending HTTP status codes using the

header()

function.

Redirecting Users

To redirect users to another page, you can send a 302 Found status code along with a Location header:


header("HTTP/1.1 302 Found"); header("Location: http://example.com/new_page.php"); exit;

Alternatively, you can use the

$http_response_code

parameter to set the response code:


header("Location: http://example.com/new_page.php", true, 302); exit;

Handling 404 Not Found Errors

If a requested resource is not found, you can send a 404 Not Found status code and display a custom error page:


header("HTTP/1.1 404 Not Found"); include("404_error_page.php"); exit;

Preventing Browser Caching

To prevent browsers from caching your page, you can send appropriate headers with your response:


header("Cache-Control: no-cache, no-store, must-revalidate"); header("Pragma: no-cache"); header("Expires: 0");

HTTP Headers In PHP - Request & Response Headers - Full PHP 8 Tutorial
HTTP Headers In PHP – Request & Response Headers – Full PHP 8 Tutorial

Conclusion

Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is essential for proper communication between the server and the client.

Kickstart Your Career

Get certified by completing the course

Get Started

In this tutorial, we will explore PHP’s

header()

function and its use for sending HTTP status codes from the server to the client. We will demonstrate how to send different HTTP status codes using the

header()

function and how to handle common use cases within your PHP applications. By the end of this tutorial, you should have a solid understanding of the

header()

function and how to use it effectively in your projects.

Creating Responses

Strings and Arrays

All routes and controllers should return a response to be sent back to the user’s browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:

Route::get(‘/’, function () {return ‘Hello World’;});

In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:

Route::get(‘/’, function () {return [1, 2, 3];});

[!NOTE]

Did you know you can also return Eloquent collections from your routes or controllers? They will automatically be converted to JSON. Give it a shot!

Response Objects

Typically, you won’t just be returning simple strings or arrays from your route actions. Instead, you will be returning full

Illuminate\Http\Response

instances or views.

Returning a full

Response

instance allows you to customize the response’s HTTP status code and headers. A

Response

instance inherits from the

Symfony\Component\HttpFoundation\Response

class, which provides a variety of methods for building HTTP responses:

Route::get(‘/home’, function () {return response(‘Hello World’, 200)->header(‘Content-Type’, ‘text/plain’);});

Eloquent Models and Collections

You may also return Eloquent ORM models and collections directly from your routes and controllers. When you do, Laravel will automatically convert the models and collections to JSON responses while respecting the model’s hidden attributes:

use App\Models\User;Route::get(‘/user/{user}’, function (User $user) {return $user;});

Attaching Headers to Responses

Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the

header

method to add a series of headers to the response before sending it back to the user:

return response($content)->header(‘Content-Type’, $type)->header(‘X-Header-One’, ‘Header Value’)->header(‘X-Header-Two’, ‘Header Value’);

Or, you may use the

withHeaders

method to specify an array of headers to be added to the response:

return response($content)->withHeaders([‘Content-Type’ => $type,’X-Header-One’ => ‘Header Value’,’X-Header-Two’ => ‘Header Value’,]);

Cache Control Middleware

Laravel includes a

cache.headers

middleware, which may be used to quickly set the

Cache-Control

header for a group of routes. Directives should be provided using the “snake case” equivalent of the corresponding cache-control directive and should be separated by a semicolon. If

etag

is specified in the list of directives, an MD5 hash of the response content will automatically be set as the ETag identifier:

Route::middleware(‘cache.headers:public;max_age=2628000;etag’)->group(function () {Route::get(‘/privacy’, function () {// …});Route::get(‘/terms’, function () {// …});});

Attaching Cookies to Responses

You may attach a cookie to an outgoing

Illuminate\Http\Response

instance using the

cookie

method. You should pass the name, value, and the number of minutes the cookie should be considered valid to this method:

return response(‘Hello World’)->cookie(‘name’, ‘value’, $minutes);

The

cookie

method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP’s native setcookie method:

return response(‘Hello World’)->cookie(‘name’, ‘value’, $minutes, $path, $domain, $secure, $httpOnly);

If you would like to ensure that a cookie is sent with the outgoing response but you do not yet have an instance of that response, you can use the

Cookie

facade to “queue” cookies for attachment to the response when it is sent. The

queue

method accepts the arguments needed to create a cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

use Illuminate\Support\Facades\Cookie;Cookie::queue(‘name’, ‘value’, $minutes);

Generating Cookie Instances

If you would like to generate a

Symfony\Component\HttpFoundation\Cookie

instance that can be attached to a response instance at a later time, you may use the global

cookie

helper. This cookie will not be sent back to the client unless it is attached to a response instance:

$cookie = cookie(‘name’, ‘value’, $minutes);return response(‘Hello World’)->cookie($cookie);

Expiring Cookies Early

You may remove a cookie by expiring it via the

withoutCookie

method of an outgoing response:

return response(‘Hello World’)->withoutCookie(‘name’);

If you do not yet have an instance of the outgoing response, you may use the

Cookie

facade’s

expire

method to expire a cookie:

Cookie::expire(‘name’);

Cookies and Encryption

By default, all cookies generated by Laravel are encrypted and signed so that they can’t be modified or read by the client. If you would like to disable encryption for a subset of cookies generated by your application, you may use the

$except

property of the

App\Http\Middleware\EncryptCookies

middleware, which is located in the

app/Http/Middleware

directory:

/*** The names of the cookies that should not be encrypted.** @var array*/protected $except = [‘cookie_name’,];

Get status code from API in php in minutes!
Get status code from API in php in minutes!

Conclusion

In this tutorial, we’ve covered the basics of PHP’s

header()

function and how to use it for sending HTTP status codes. We also discussed some common use cases for sending HTTP status codes, such as redirecting users, handling 404 errors, and preventing browser caching. Now that you have a better understanding of the

header()

function, you can use it effectively in your PHP applications. If you’re looking to hire PHP developers who are skilled in using the

header()

function, reach out to Reintech today.

HTTP Responses

  • Creating Responses
  • Redirects
  • Other Response Types
  • Response Macros

Returning A Status Code In PHP

To return a status code in PHP, the simplest way is to use the http_response_code() function, along with the relevant HTTP status code parameter into your website, followed by the exit() command which stops any more output being set.

This means the likes of 400 bad requests and 404 not found can all be implemented with just one line of code.

Important: The http_response_code and header() commands must be used before any HTML is returned.

Example: Return a 400 bad request status code


http_response_code(400); exit;

Example: Return a 404 not found status code


http_response_code(404); exit;

Example: Return a 301 moved permanently status code

This example php code also requires that you provide the new URL, to which the users browser will automatically redirect. For this you need to use the more details header() function.


http_response_code(301); header('Location: /newlocation.html'); exit;

The exit command means that no other php code or html code will be output from the page.

Here’s example code for a 503 temporary error page that also includes additional information that is shown in the browser.



<br /> php-generated 503<br />


This is a 503 error page. The error is returned in the HTTP header and this is just simple HTML that is displayed in the browser.


HTTP Status Codes Explained In 5 Minutes
HTTP Status Codes Explained In 5 Minutes

Sending HTTP Status Codes with `header()`

To send an HTTP status code using the

header()

function, you need to provide a header string in the format

"HTTP/x.y STATUS_CODE STATUS_MESSAGE"

, where

x.y

is the HTTP protocol version (e.g., 1.1),

STATUS_CODE

is the 3-digit status code (e.g., 200), and

STATUS_MESSAGE

is the corresponding status message (e.g., “OK”).

Here’s an example of sending a 200 OK status code:


header("HTTP/1.1 200 OK");

And here’s an example of sending a 404 Not Found status code:


header("HTTP/1.1 404 Not Found");

PHP – An Overview

PHP stands for hypertext preprocessor. As you may have noticed, the acronym is a little confusing and that’s because PHP originally stood for personal home page. Remember, the way we develop websites has changed immensely in the short time the internet has existed, so sometimes terms need to be updated to keep up to modern standards.

Whenever you request a URL, a complex chain occurs between the server and the browser. PHP is usually involved in this process, as it’s responsible for interpreting the data. A common example of where you would see PHP in action is a login page. As you enter your credentials, a request to the server is made, and PHP will communicate with the database to log you in.

Essentially, PHP is a scripting language that is embedded into HTML. For a quick example, left click on any webpage and select ‘view page source’. Doing so will bring up the code that makes up that page. It is your browser that interprets the code into the functional version of the website.

With PHP, code can either be processed client side (HTML, Javascript and CSS) or server side (PHP). In essence, the server side of PHP is software that is installed on the server. This software can include Linux, Apache, MySQL and finally PHP. In that order, these 4 elements make up what’s known as a LAMP stack. The PHP is the scripting layer of this combination which websites and web applications run off.

PHP-Send HTTP Get/Post Request and Read JSON response
PHP-Send HTTP Get/Post Request and Read JSON response

What are Status Codes?

HTTP status codes are a way that servers communicate with clients (browsers). For the most part, the page loads successfully and so an ‘ok’ 2xx code will be generated. In such a case, status codes remain invisible to the user. But status codes are there to cover all eventualities, such as a 404 error or even a 502 bad gateway, which will be visually displayed on the page as an error message.

Understanding status codes will allow you to enhance your user experience, especially if your website visitors are receiving error codes that originate from your server as an example.

As the practice is quite technical, status codes are usually implemented manually by someone who understands coding such as a web developer. However, if your website is on WordPress, then plugins do exist to help you make sense and implement status codes.

Of course, as a website user, you may also come across status codes on other websites too. For example, 403 forbidden can be generated if you try to access a section of a website that you don’t have permission to view.

Technical Details

Return Value: If code is set, the previous status code is returned. If code is not set, the current status code is returned
PHP Version: 5.4+

❮ PHP Network Reference

Status codes, the status of a p[age being requested from a web server can be generated in a number of different ways. Here we show you how this is done in PHP code – a language that can be used to generate HTML web pages directly.

  • Why use PHP to generate status codes?
  • What are Status Codes?
  • HTTP Status Code Types – Overview
  • PHP – An Overview
  • Returning A Status Code In PHP
  • Example: Return a 400 bad request status code
  • Example: Return a 404 not found status code
  • Example: Return a 301 moved permanently status code
  • Why Status Codes Matters For SEO
  • Further Reading

When browsing the internet as a user, you are probably unaware of the secret messaging that is being sent back and forth between where the website is being hosted and your browser.

For example, domain names are actually a series of numerical combinations. Status codes are similar in that they give information about if a page has loaded successfully or not, and the root cause of any errors. PHP is a scripting language that can generate status-code data.

While your content management system, possibly (WordPress) and your web server (possibly Apache) can generate these codes, the scripting language PHP, which is the basis of WordPress, can also generate these codes.

Real-Time Chat Application in PHP MySQL CodeIgniter with Source Code - CodeAstro
Real-Time Chat Application in PHP MySQL CodeIgniter with Source Code – CodeAstro

Further Reading

The above gives a brief overview of returning status codes in PHP. However, given the complex nature of coding it’s impossible to cover everything in just one article alone. So we definitely suggest doing some further reading to increase your understanding.

Resources you may find helpful include the official PHP website. In particular, their Using PHP section covers common errors you may encounter, especially as you get to grips with it.

Remember, when building any code it’s essential to test it. Even a small error or even a bug can disrupt the final result, so it’s good to remember that PHP isn’t just about the writing of the script, but seeing it through to a working page. Plus, looking out for any errors that may occur further down the line.

Dù có là 1 lập trình viên web hay không, chắc hẳn bạn cũng đã bắt gặp HTTP status code (mã trạng thái HTTP) ít nhất 1 hay nhiều lần rồi đúng không nào?

200, 404, 500… đều là những HTTP status code phổ biến. Thậm chí các truyện vui hay ảnh chế meme về 404 cũng khá nổi tiếng và đầy rẫy trên mạng Internet mà hầu hết bất kỳ ai cũng có thể hiểu được.

Vậy thì có bao giờ bạn thắc mắc HTTP status code là gì và ý nghĩa các con số của chúng hay chưa? Hôm nay chúng ta sẽ nói tổng quát 1 chút về HTTP status code và ý nghĩa nằm ẩn sau các con số đó nhé!

Using the http_response_code header with header() function

Using the http_response_code header with the header() function is another method to send an HTTP response code in PHP. Here’s how you can use it:

In this example, the header() function is used to set the HTTP response code to 200 (OK). The “http/1.1” specifies the version of the HTTP protocol, and “200 OK” is the response status line.

You can replace “200 OK” with any valid HTTP response status line, such as “404 Not Found”, “500 Internal Server Error”, or “301 Moved Permanently”, depending on the desired response code.

Here’s an example of sending a 404 (Not Found) response code:

When using this method, you need to specify the full response status line, including the HTTP version, in the header() function.

It’s important to note that the header() function should be called before any output is sent to the client, as headers must be sent before the response body.

This method is available in all versions of PHP and provides flexibility in setting the response code using the http_response_code header with the header() function.

Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is crucial for proper communication between the server and the client.

Live notification using PHP & Pure JavaScript AJAX #PHP #liveNotification
Live notification using PHP & Pure JavaScript AJAX #PHP #liveNotification

List of Functions to Manipulate Responses

As we have already covered, exchanging data on the Internet consists of one side (client) asking for specific data and the other (server) supplying the requested information. A piece of data that server issues as an answer to a particular request is called a PHP HTTP response.

Response has the same structure as request. It consists of a status line, header and body. To set a certain PHP HTTP response, you should use

http_response_code()

function.

Now, there are various ways to control these responses. Let’s see them in a table below:

Function Description
header() Send raw HTTP header to client
headers_list() Return list of PHP HTTP response headers already sent (or headers that are ready to be sent)
headers_sent() Check if / where HTTP headers have been sent
setcookie() Set cookie to send along with remaining HTTP headers
setrawcookie() Set cookie (without URL encoding) to send along with remaining HTTP headers

HTTP Status Code – Mã trạng thái HTTP là gì?

Khi được nhận và phiên dịch 1 yêu cầu HTTP từ phía client, HTTP status code sẽ được máy chủ cung cấp để đáp ứng yêu cầu đó của họ. Nó bao gồm code từ IETF Request for Comments (RFC), các thông số kỹ thuật khác và 1 số code bổ sung được sử dụng trong 1 số ứng dụng phổ biến của giao thức HTTP.

Chữ số đầu tiên của HTTP status code chỉ định 1 trong 5 loại phản hồi quy chuẩn. Các cụm tin nhắn được hiển thị chỉ mang tính tượng trưng, nhưng cũng có thể cung cấp bất kỳ thông tin bổ sung nào để chúng ta có thể đọc được. Trừ khi có những chỉ định khác, HTTP status code được xem như 1 phần của quy chuẩn HTTP/1.1 (RFC 7231).

Cơ Quan Cấp Số Được Ấn Định Trên Internet (tức IANA hay The Internet Assigned Numbers Authority) chính là nơi duy trì sổ đăng ký chính thức của các HTTP status code.

PHP REST API CRUD 2: Create API to Insert/Store data in php mysql | Insert Data using API in PHP
PHP REST API CRUD 2: Create API to Insert/Store data in php mysql | Insert Data using API in PHP

Sending HTTP Status Codes with `header()`

To send an HTTP status code using the

header()

function, you need to provide a header string in the format

"HTTP/x.y STATUS_CODE STATUS_MESSAGE"

, where

x.y

is the HTTP protocol version (e.g., 1.1),

STATUS_CODE

is the 3-digit status code (e.g., 200), and

STATUS_MESSAGE

is the corresponding status message (e.g., “OK”).

Here’s an example of sending a 200 OK status code:


header("HTTP/1.1 200 OK");

And here’s an example of sending a 404 Not Found status code:


header("HTTP/1.1 404 Not Found");

Technical Details

Return Value: If code is set, the previous status code is returned. If code is not set, the current status code is returned
PHP Version: 5.4+

❮ PHP Network Reference

/**
* Content from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
* You may also want a list of unofficial codes:
* 103 => ‘Checkpoint’,
* 218 => ‘This is fine’, // Apache Web Server
* 419 => ‘Page Expired’, // Laravel Framework
* 420 => ‘Method Failure’, // Spring Framework
* 420 => ‘Enhance Your Calm’, // Twitter
* 430 => ‘Request Header Fields Too Large’, // Shopify
* 450 => ‘Blocked by Windows Parental Controls’, // Microsoft
* 498 => ‘Invalid Token’, // Esri
* 499 => ‘Token Required’, // Esri
* 509 => ‘Bandwidth Limit Exceeded’, // Apache Web Server/cPanel
* 526 => ‘Invalid SSL Certificate’, // Cloudflare and Cloud Foundry’s gorouter
* 529 => ‘Site is overloaded’, // Qualys in the SSLLabs
* 530 => ‘Site is frozen’, // Pantheon web platform
* 598 => ‘Network read timeout error’, // Informal convention
* 440 => ‘Login Time-out’, // IIS
* 449 => ‘Retry With’, // IIS
* 451 => ‘Redirect’, // IIS
* 444 => ‘No Response’, // nginx
* 494 => ‘Request header too large’, // nginx
* 495 => ‘SSL Certificate Error’, // nginx
* 496 => ‘SSL Certificate Required’, // nginx
* 497 => ‘HTTP Request Sent to HTTPS Port’, // nginx
* 499 => ‘Client Closed Request’, // nginx
* 520 => ‘Web Server Returned an Unknown Error’, // Cloudflare
* 521 => ‘Web Server Is Down’, // Cloudflare
* 522 => ‘Connection Timed Out’, // Cloudflare
* 523 => ‘Origin Is Unreachable’, // Cloudflare
* 524 => ‘A Timeout Occurred’, // Cloudflare
* 525 => ‘SSL Handshake Failed’, // Cloudflare
* 526 => ‘Invalid SSL Certificate’, // Cloudflare
* 527 => ‘Railgun Error’, // Cloudflare
*/
return [
100 => ‘Continue’,
101 => ‘Switching Protocols’,
102 => ‘Processing’, // WebDAV; RFC 2518
103 => ‘Early Hints’, // RFC 8297
200 => ‘OK’,
201 => ‘Created’,
202 => ‘Accepted’,
203 => ‘Non-Authoritative Information’, // since HTTP/1.1
204 => ‘No Content’,
205 => ‘Reset Content’,
206 => ‘Partial Content’, // RFC 7233
207 => ‘Multi-Status’, // WebDAV; RFC 4918
208 => ‘Already Reported’, // WebDAV; RFC 5842
226 => ‘IM Used’, // RFC 3229
300 => ‘Multiple Choices’,
301 => ‘Moved Permanently’,
302 => ‘Found’, // Previously “Moved temporarily”
303 => ‘See Other’, // since HTTP/1.1
304 => ‘Not Modified’, // RFC 7232
305 => ‘Use Proxy’, // since HTTP/1.1
306 => ‘Switch Proxy’,
307 => ‘Temporary Redirect’, // since HTTP/1.1
308 => ‘Permanent Redirect’, // RFC 7538
400 => ‘Bad Request’,
401 => ‘Unauthorized’, // RFC 7235
402 => ‘Payment Required’,
403 => ‘Forbidden’,
404 => ‘Not Found’,
405 => ‘Method Not Allowed’,
406 => ‘Not Acceptable’,
407 => ‘Proxy Authentication Required’, // RFC 7235
408 => ‘Request Timeout’,
409 => ‘Conflict’,
410 => ‘Gone’,
411 => ‘Length Required’,
412 => ‘Precondition Failed’, // RFC 7232
413 => ‘Payload Too Large’, // RFC 7231
414 => ‘URI Too Long’, // RFC 7231
415 => ‘Unsupported Media Type’, // RFC 7231
416 => ‘Range Not Satisfiable’, // RFC 7233
417 => ‘Expectation Failed’,
418 => ‘I\’m a teapot’, // RFC 2324, RFC 7168
421 => ‘Misdirected Request’, // RFC 7540
422 => ‘Unprocessable Entity’, // WebDAV; RFC 4918
423 => ‘Locked’, // WebDAV; RFC 4918
424 => ‘Failed Dependency’, // WebDAV; RFC 4918
425 => ‘Too Early’, // RFC 8470
426 => ‘Upgrade Required’,
428 => ‘Precondition Required’, // RFC 6585
429 => ‘Too Many Requests’, // RFC 6585
431 => ‘Request Header Fields Too Large’, // RFC 6585
451 => ‘Unavailable For Legal Reasons’, // RFC 7725
500 => ‘Internal Server Error’,
501 => ‘Not Implemented’,
502 => ‘Bad Gateway’,
503 => ‘Service Unavailable’,
504 => ‘Gateway Timeout’,
505 => ‘HTTP Version Not Supported’,
506 => ‘Variant Also Negotiates’, // RFC 2295
507 => ‘Insufficient Storage’, // WebDAV; RFC 4918
508 => ‘Loop Detected’, // WebDAV; RFC 5842
510 => ‘Not Extended’, // RFC 2774
511 => ‘Network Authentication Required’, // RFC 6585
];

angeldelrio
commented
May 20, 2018

Just was I was looking for. Thanks!

rajeshkumar-arch
commented
Jun 20, 2018

Thanks

ghost
commented
Jul 1, 2018

Thanks!

benfavre
commented
Aug 7, 2018

Thanks !! <3

prajyotpro
commented
Aug 17, 2018

much needed. Thanks

romanzhivo
commented
May 20, 2019

A lot of thanks! 🙂

zanderwar
commented
Jul 18, 2019

420, 424, 451 have duplicate entries, the former would never be revealed may as well remove them

pavrip
commented
Feb 23, 2020

Thank you for this

hondero2552
commented
Apr 2, 2020

THANK YOU!! Just what I was looking for!

ramirespoa
commented
Apr 9, 2020

Thank you!

hiperesp
commented
Apr 11, 2020

Thank you!

cristiancarrino
commented
May 10, 2020

<3

shapyz
commented
Nov 21, 2020

Thank you

gaffling
commented
Apr 3, 2021

$http_status_codes = array(100 => ‘Continue’,101 => ‘Switching Protocols’,102 => ‘Processing’,200 => ‘OK’,201 => ‘Created’,202 => ‘Accepted’,203 => ‘Non-Authoritative Information’,204 => ‘No Content’,205 => ‘Reset Content’,206 => ‘Partial Content’,207 => ‘Multi-Status’,300 => ‘Multiple Choices’,301 => ‘Moved Permanently’,302 => ‘Found’,303 => ‘See Other’,304 => ‘Not Modified’,305 => ‘Use Proxy’,306 => ‘(Unused)’,307 => ‘Temporary Redirect’,308 => ‘Permanent Redirect’,400 => ‘Bad Request’,401 => ‘Unauthorized’,402 => ‘Payment Required’,403 => ‘Forbidden’,404 => ‘Not Found’,405 => ‘Method Not Allowed’,406 => ‘Not Acceptable’,407 => ‘Proxy Authentication Required’,408 => ‘Request Timeout’,409 => ‘Conflict’,410 => ‘Gone’,411 => ‘Length Required’,412 => ‘Precondition Failed’,413 => ‘Request Entity Too Large’,414 => ‘Request-URI Too Long’,415 => ‘Unsupported Media Type’,416 => ‘Requested Range Not Satisfiable’,417 => ‘Expectation Failed’,418 => “I’m a teapot”,419 => ‘Authentication Timeout’,420 => ‘Enhance Your Calm’,422 => ‘Unprocessable Entity’,423 => ‘Locked’,424 => ‘Failed Dependency’,424 => ‘Method Failure’,425 => ‘Unordered Collection’,426 => ‘Upgrade Required’,428 => ‘Precondition Required’,429 => ‘Too Many Requests’,431 => ‘Request Header Fields Too Large’,444 => ‘No Response’,449 => ‘Retry With’,450 => ‘Blocked by Windows Parental Controls’,451 => ‘Unavailable For Legal Reasons’,494 => ‘Request Header Too Large’,495 => ‘Cert Error’,496 => ‘No Cert’,497 => ‘HTTP to HTTPS’,499 => ‘Client Closed Request’,500 => ‘Internal Server Error’,501 => ‘Not Implemented’,502 => ‘Bad Gateway’,503 => ‘Service Unavailable’,504 => ‘Gateway Timeout’,505 => ‘HTTP Version Not Supported’,506 => ‘Variant Also Negotiates’,507 => ‘Insufficient Storage’,508 => ‘Loop Detected’,509 => ‘Bandwidth Limit Exceeded’,510 => ‘Not Extended’,511 => ‘Network Authentication Required’,598 => ‘Network read timeout error’,599 => ‘Network connect timeout error’);

GabrieleMartini
commented
Apr 4, 2021

418 => ‘I’m a teapot’,

@gaffling Three single quotes in this string

gaffling
commented
Apr 4, 2021

@GabrieleMartini the Backslash was dropped by GitHub, but maybe a developer should be able to fix that 😉

In this tutorial, we will explore PHP’s

header()

function and its use for sending HTTP status codes from the server to the client. We will demonstrate how to send different HTTP status codes using the

header()

function and how to handle common use cases within your PHP applications. By the end of this tutorial, you should have a solid understanding of the

header()

function and how to use it effectively in your projects.

Top 5 Most Used Architecture Patterns
Top 5 Most Used Architecture Patterns

Conclusion

In this tutorial, we’ve covered the basics of PHP’s

header()

function and how to use it for sending HTTP status codes. We also discussed some common use cases for sending HTTP status codes, such as redirecting users, handling 404 errors, and preventing browser caching. Now that you have a better understanding of the

header()

function, you can use it effectively in your PHP applications. If you’re looking to hire PHP developers who are skilled in using the

header()

function, reach out to Reintech today.

HTTP stands for Hypertext Transfer Protocol. It is called a protocol of request-response type. That means it functions by the server answering various requests it receives from the client (in this case, the Internet browser).

In this tutorial, we will explain in more detail what a PHP HTTP response is, how to set and modify it. Such a response can be modified in numerous ways, but to do that, a developer must have some knowledge on special functions.

Contents

Redirects

Redirect responses are instances of the

Illuminate\Http\RedirectResponse

class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a

RedirectResponse

instance. The simplest method is to use the global

redirect

helper:

Route::get(‘/dashboard’, function () {return redirect(‘home/dashboard’);});

Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global

back

helper function. Since this feature utilizes the session, make sure the route calling the

back

function is using the

web

middleware group:

Route::post(‘/user/profile’, function () {// Validate the request…return back()->withInput();});

Redirecting to Named Routes

When you call the

redirect

helper with no parameters, an instance of

Illuminate\Routing\Redirector

is returned, allowing you to call any method on the

Redirector

instance. For example, to generate a

RedirectResponse

to a named route, you may use the

route

method:

return redirect()->route(‘login’);

If your route has parameters, you may pass them as the second argument to the

route

method:

// For a route with the following URI: /profile/{id}return redirect()->route(‘profile’, [‘id’ => 1]);

Populating Parameters via Eloquent Models

If you are redirecting to a route with an “ID” parameter that is being populated from an Eloquent model, you may pass the model itself. The ID will be extracted automatically:

// For a route with the following URI: /profile/{id}return redirect()->route(‘profile’, [$user]);

If you would like to customize the value that is placed in the route parameter, you can specify the column in the route parameter definition (

/profile/{id:slug}

) or you can override the

getRouteKey

method on your Eloquent model:

/*** Get the value of the model’s route key.*/public function getRouteKey(): mixed{return $this->slug;}

Redirecting to Controller Actions

You may also generate redirects to controller actions. To do so, pass the controller and action name to the

action

method:

use App\Http\Controllers\UserController;return redirect()->action([UserController::class, ‘index’]);

If your controller route requires parameters, you may pass them as the second argument to the

action

method:

return redirect()->action([UserController::class, ‘profile’], [‘id’ => 1]);

Redirecting to External Domains

Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the

away

method, which creates a

RedirectResponse

without any additional URL encoding, validation, or verification:

return redirect()->away(‘https://www.google.com’);

Redirecting With Flashed Session Data

Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a

RedirectResponse

instance and flash data to the session in a single, fluent method chain:

Route::post(‘/user/profile’, function () {// …return redirect(‘dashboard’)->with(‘status’, ‘Profile updated!’);});

After the user is redirected, you may display the flashed message from the session. For example, using Blade syntax:

@if (session(‘status’))

{{ session(‘status’) }}

@endif

Redirecting With Input

You may use the

withInput

method provided by the

RedirectResponse

instance to flash the current request’s input data to the session before redirecting the user to a new location. This is typically done if the user has encountered a validation error. Once the input has been flashed to the session, you may easily retrieve it during the next request to repopulate the form:

return back()->withInput();

How To Create A Simple REST API in PHP
How To Create A Simple REST API in PHP

Common Use Cases for HTTP Status Codes

In this section, we will show you some common use cases for sending HTTP status codes using the

header()

function.

Redirecting Users

To redirect users to another page, you can send a 302 Found status code along with a Location header:


header("HTTP/1.1 302 Found"); header("Location: http://example.com/new_page.php"); exit;

Alternatively, you can use the

$http_response_code

parameter to set the response code:


header("Location: http://example.com/new_page.php", true, 302); exit;

Handling 404 Not Found Errors

If a requested resource is not found, you can send a 404 Not Found status code and display a custom error page:


header("HTTP/1.1 404 Not Found"); include("404_error_page.php"); exit;

Preventing Browser Caching

To prevent browsers from caching your page, you can send appropriate headers with your response:


header("Cache-Control: no-cache, no-store, must-revalidate"); header("Pragma: no-cache"); header("Expires: 0");


Status codes as an array:

$http_status_codes = array(100 => "Continue", 101 => "Switching Protocols", 102 => "Processing", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 306 => "(Unused)", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Request Entity Too Large", 414 => "Request-URI Too Long", 415 => "Unsupported Media Type", 416 => "Requested Range Not Satisfiable", 417 => "Expectation Failed", 418 => "I'm a teapot", 419 => "Authentication Timeout", 420 => "Enhance Your Calm", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 424 => "Method Failure", 425 => "Unordered Collection", 426 => "Upgrade Required", 428 => "Precondition Required", 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 444 => "No Response", 449 => "Retry With", 450 => "Blocked by Windows Parental Controls", 451 => "Unavailable For Legal Reasons", 494 => "Request Header Too Large", 495 => "Cert Error", 496 => "No Cert", 497 => "HTTP to HTTPS", 499 => "Client Closed Request", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", 505 => "HTTP Version Not Supported", 506 => "Variant Also Negotiates", 507 => "Insufficient Storage", 508 => "Loop Detected", 509 => "Bandwidth Limit Exceeded", 510 => "Not Extended", 511 => "Network Authentication Required", 598 => "Network read timeout error", 599 => "Network connect timeout error");?>Source: Wikipedia "List_of_HTTP_status_codes"

I have a PHP script that needs to make responses with HTTP response codes (status-codes), like HTTP 200 OK, or some 4XX or 5XX code.

How can I do this in PHP?

I have a PHP script that needs to make responses with HTTP response codes (status-codes), like HTTP 200 OK, or some 4XX or 5XX code.

How can I do this in PHP?

I just found this question and thought it needs a more comprehensive answer:

As of PHP 5.4 there are three methods to accomplish this:

The

header()

function has a special use-case that detects a HTTP response line and lets you replace that with a custom one


header("HTTP/1.1 200 OK");

However, this requires special treatment for (Fast)CGI PHP:


$sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') header("Status: 404 Not Found"); else header("HTTP/1.1 404 Not Found");

Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.

Note:

php_sapi_name()

requires PHP 4.0.1

There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.

Since 4.3, the

header

function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:


header(':', true, 404); header('X-PHP-Response-Code: 404', true, 404);

I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.

The

http_response_code()

function was introduced in PHP 5.4, and it made things a lot easier.


http_response_code(404);

That’s all.

Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the “new”

http_response_code

function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know…


// For 4.3.0 <= PHP <= 5.4.0 if (!function_exists('http_response_code')) { function http_response_code($newcode = NULL) { static $code = 200; if($newcode !== NULL) { header('X-PHP-Response-Code: '.$newcode, true, $newcode); if(!headers_sent()) $code = $newcode; } return $code; } }


headers_sent()is true if you can't add any more headers because content was already sent, not if you have added a header. (2) Sorry, no. Other languages have better support though


http_response_code(and maybe more generally modifying the header) doesn't work anymore after you


echosomething. Hope it helps.


http_response_code()cannot be used to invent custom error codes. For example


http_response_code(930)will cause the apache log file to show 930 correctly, but an error 500 will actually be sent back to the client. Use the


header()method instead for this admittedly weird use case.


http_response_code()is unreliable for reading the status code. Heders set using


header()take precedence, and


HTTP/1.1

format takes precedence over


Status:


format - at least on FCGI & nginx.

Unfortunately I found solutions presented by @dualed have various flaws.

Using

substr($sapi_type, 0, 3) == 'cgi'

is not enogh to detect fast CGI. When using PHP-FPM FastCGI Process Manager,

php_sapi_name()

returns fpm not cgi

Fasctcgi and php-fpm expose another bug mentioned by @Josh - using

header('X-PHP-Response-Code: 404', true, 404);

does work properly under PHP-FPM (FastCGI)


header("HTTP/1.1 404 Not Found");

may fail when the protocol is not HTTP/1.1 (i.e. 'HTTP/1.0'). Current protocol must be detected using

$_SERVER['SERVER_PROTOCOL']

(available since PHP 4.1.0)

There are at least 2 cases when calling

http_response_code()

result in unexpected behaviour:

For your reference here there is the full list of HTTP response status codes (this list includes codes from IETF internet standards as well as other IETF RFCs. Many of them are NOT currently supported by PHP http_response_code function()): http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

You can easily test this bug by calling:


http_response_code(521);

The server will send "500 Internal Server Error" HTTP response code resulting in errors if you have a custom client application expecting additional HTTP codes.

My solution (for all PHP versions since 4.1.0):


$httpStatusCode = 521; $httpStatusMsg = 'Web server is down'; $phpSapiName = substr(php_sapi_name(), 0, 3); if ($phpSapiName == 'cgi' || $phpSapiName == 'fpm') { header('Status: '.$httpStatusCode.' '.$httpStatusMsg); } else { $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0'; header($protocol.' '.$httpStatusCode.' '.$httpStatusMsg); }

Conclusion

http_response_code() implementation does not support all HTTP response codes and may overwrite the specified HTTP response code with another one from the same group.

The new http_response_code() function does not solve all the problems involved but make things worst introducing new bugs.

The "compatibility" solution offered by @dualed does not work as expected, at least under PHP-FPM.

The other solutions offered by @dualed also have various bugs. Fast CGI detection does not handle PHP-FPM. Current protocol must be detected.

Any tests and comments are appreciated.

Since PHP 5.4 you can use

http_response_code()

for get and set header status code.

Here is an example:

Here is the document of this function in php.net:

Add this line before any output of the body, in the event you aren't using output buffering.


header("HTTP/1.1 200 OK");

Replace the message portion ('OK') with the appropriate message, and the status code with your code as appropriate (404, 501, etc)

If you are here because of WordPress giving 404's when loading the environment, this should fix the problem:


define('WP_USE_THEMES', false); require('../wp-blog-header.php'); status_header( 200 ); //$wp_query->is_404=false; // if necessary

The problem is due to it sending a Status: 404 Not Found header. You have to override that. This will also work:


define('WP_USE_THEMES', false); require('../wp-blog-header.php'); header("HTTP/1.1 200 OK"); header("Status: 200 All rosy");

With the header function. There is an example in the section on the first parameter it takes.


header("HTTP/1.1 200 OK"); http_response_code(201); header("Status: 200 All rosy");

http_response_code(200); not work because test alert 404 https://developers.google.com/speed/pagespeed/insights/


PHP http_response_code() Function

Example

Set the HTTP response status code to 404:


http_response_code(404);?>

http_response_code(404);

?>

Create a Simple API In PHP with MySQL Database
Create a Simple API In PHP with MySQL Database

What is the `header()` Function?

The

header()

function is a built-in PHP function that allows you to send raw HTTP headers to the client. It is commonly used to set the Content-Type, redirect users, and send HTTP status codes. The syntax for the

header()

function is as follows:


header(string $header, bool $replace = true, int $http_response_code = 0)

Here are the function parameters:

  • $header: The header string to send.
  • $replace: (Optional) Indicates whether the header should replace the previously set header with the same name. If set to

    false

    , the new header will be added alongside any existing headers with the same name. The default value is

    true

    .
  • $http_response_code: (Optional) Forces the HTTP response code to the specified value. The default value is , which means the response code is not modified.

Using the header() function

Using the header() function is another method to send an HTTP response code in PHP.

Here’s how you can use it:

In this example, the header() function is used to set the HTTP response code to 200 (OK). The HTTP/1.1 specifies the version of the HTTP protocol, and 200 OK is the response status line.

You can replace “200 OK” with any valid HTTP response status line, such as “404 Not Found”, “500 Internal Server Error”, or “301 Moved Permanently”, depending on the desired response code.

Here’s an example of sending a 404 (Not Found) response code:

The header() function allows you to set various HTTP headers, including the response code. It should be called before any output is sent to the client, as headers must be sent before the response body.

It’s important to note that when using the header() function to set the response code, you need to specify the full response status line, including the HTTP version. The function is available in all versions of PHP.

Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is crucial for proper communication between the server and the client.

PHP Chat application (Complete Project) [+SOURCE CODE]
PHP Chat application (Complete Project) [+SOURCE CODE]

Using the Response class in a PHP framework

Using the Response class in a PHP framework is another method to send an HTTP response code. This method is specific to PHP frameworks such as Laravel, Symfony, or CodeIgniter. The exact implementation may vary depending on the framework you are using.

Here’s an example using Laravel


setStatusCode(200); ?>

In this example, the response() function is used to create an instance of the Response class. The empty string ” passed as the content represents an empty response body. Then, the setStatusCode() method is used to set the HTTP response code to 200 (OK).

You can replace 200 with any valid HTTP response code according to your requirements. Additionally, you can provide content as a parameter to the response() function if you want to send a response body along with the code.

The Response class in PHP frameworks provides various methods to customize the response, such as setting headers, adding cookies, and setting the content type.

The exact syntax and methods may differ depending on the PHP framework you are using. Refer to the documentation of your specific framework to learn more about using the Response class to send an HTTP response code.

Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is essential for proper communication between the server and the client.

Danh sách đầy đủ các HTTP status code (code + cụm từ chỉ lý do):

Information responses / Phản hồi thông tin:

– 100 Continue: Phản hồi tạm thời này cho biết rằng mọi thứ tới hiện tại vẫn ổn và phía client nên tiếp tục yêu cầu hay bỏ qua phản hồi nếu yêu cầu đã hoàn tất.

– 101 Switching Protocol: Code này được gửi để phản hồi header yêu cầu Upgrade từ phía client và cho biết giao thức máy chủ đang chuyển sang.

– 102 Processing (WebDAV): Code này cho biết rằng máy chủ đã nhận và đang xử lý yêu cầu, nhưng phản hồi vẫn chưa có hiệu lực.

– 103 Early Hints: Được sử dụng để trả về một số tiêu đề phản hồi trước message HTTP cuối cùng.

Successful responses / Phản hồi thành công:

– 200 OK: Yêu cầu đã thành công. Ý nghĩa của thành công còn phụ thuộc vào phương thức HTTP là gì:

GET: Tài nguyên đã được tìm nạp và được truyền trong nội dung thông điệp.HEAD: Các header thực thể nằm trong nội dung thông điệp.PUT hoặc POST: Tài nguyên mô tả kết quả của hành động được truyền trong nội dung thông điệp.TRACE: Nội dung thông điệp chứa thông báo yêu cầu khi máy chủ nhận được.

– 201 Created: Yêu cầu đã thành công và kết quả là một tài nguyên mới đã được tạo. Đây thường là phản hồi được gửi sau các yêu cầu POST hoặc một số yêu cầu PUT.

– 202 Accepted: Yêu cầu đã được nhận nhưng chưa được thực hiện. Yêu cầu này là non-committal, vì không có cách nào trong HTTP để gửi sau đó một phản hồi không đồng bộ cho biết kết quả của yêu cầu. Nó dành cho các trường hợp trong đó 1 quá trình / máy chủ khác xử lý yêu cầu hoặc để xử lý hàng loạt.

– 203 Non-Authoritative Information: Code phản hồi này có nghĩa là siêu thông tin được trả về không hoàn toàn giống với thông tin có sẵn từ máy chủ gốc, nhưng được thu thập từ phần copy local hay của bên phía thứ 3. Code này chủ yếu được sử dụng để phản chiếu hoặc sao lưu tài nguyên khác. Ngoại trừ trường hợp cụ thể đó, thông thường phản hồi “200 OK” được ưu tiên cho trạng thái này.

– 204 No Content: Không có nội dung để gửi cho yêu cầu này, nhưng các header có thể hữu dụng. User-agent có thể cập nhật các header đã lưu trong bộ nhớ cache cho tài nguyên này bằng các header mới.

– 205 Reset Content: Cho user-agent biết để reset document đã gửi yêu cầu này.

– 206 Partial Content: Code phản hồi này được dùng khi Range header được gửi từ client để yêu cầu chỉ 1 phần của nguồn tài nguyên.

– 207 Multi-Status (WebDAV): Truyền tải thông tin về nhiều nguồn tài nguyên, đối với các trường hợp mà nhiều status code có thể đều thích hợp.

– 208 Already Reported (WebDAV): Được sử dụng trong 1 phần tử phản hồi để tránh liệt kê nhiều lần các thành viên nội tại của nhiều liên kết vào cùng 1 tập hợp.

– 226 IM Used (HTTP Delta encoding): Máy chủ đã hoàn thành yêu cầu GET cho nguồn tài nguyên và phản hồi là sự trình bày kết quả của 1 hoặc nhiều thao tác instance được áp dụng cho instance hiện tại.

Redirects / Điều hướng:

– 300 Multiple Choice: Yêu cầu có thể có nhiều hơn 1 phản hồi khả dụng. User-agent hay user nên chọn 1 trong số đó. (Không có cách chuẩn hóa nào để chọn 1 trong các phản hồi, nhưng HTML liên kết đến các khả năng được khuyến nghị để user có thể chọn.)

– 301 Moved Permanently: URL của tài nguyên được yêu cầu đã được thay đổi vĩnh viễn. URL mới được đưa ra trong phần phản hồi.

– 302 Found: Code phản hồi này có nghĩa là URI của tài nguyên được yêu cầu đã được thay đổi tạm thời. Những thay đổi khác trong URI có thể được thực hiện trong tương lai. Do đó, chính URI này sẽ được client sử dụng trong các yêu cầu trong tương lai.

– 303 See Other: Máy chủ gửi phản hồi này để điều hướng client lấy nguồn tài nguyên tại 1 URI khác với 1 yêu cầu GET.

– 304 Not Modified: Code này được sử dụng cho mục đích caching. Nó cho client biết rằng phản hồi chưa được điều chỉnh, nên client có thể tiếp tục sử dụng cùng phiên bản phản hồi trong bộ nhớ cache.

– 305 Use Proxy: Được xác định trong phiên bản trước của HTTP specification để chỉ ra rằng phản hồi được yêu cầu phải được truy cập bằng proxy. Nó được yêu cầu do quan ngại về phần bảo mật liên quan đến cấu hình trong băng tần của proxy.

– 306 unused: Mã phản hồi này không còn được sử dụng nữa, nó được bảo lưu và chỉ được sử dụng trong phiên bản trước của HTTP/1.1 specification.

– 307 Temporary Redirect: Máy chủ gửi phản hồi này để điều hướng client tới lấy tài nguyên được yêu cầu tại 1 URI khác với cùng 1 phương thức đã được sử dụng trong yêu cầu trước đó. Code này có cùng ý nghĩa như code phản hồi HTTP 302 Found, ngoại trừ việc user-agent không được thay đổi phương thức HTTP sử dụng: nếu POST được dùng trong yêu cầu đầu tiên, POST phải được sử dụng trong yêu cầu thứ hai.

– 308 Permanent Redirect: Điều này có nghĩa là tài nguyên hiện được đặt cố định tại 1 URI khác, được chỉ định bởi header Location: HTTP Response. Code này có cùng ý nghĩa như code phản hồi HTTP 301 Moved Permanently, ngoại trừ việc user-agent không được thay đổi phương thức HTTP sử dụng: nếu POST được dùng trong yêu cầu đầu tiên, POST phải được sử dụng trong yêu cầu thứ hai.

Client errors / Lỗi phía client:

– 400 Bad Request: Máy chủ không thể hiểu yêu cầu do cú pháp không hợp lệ.

– 401 Unauthorized: Cho dù quy chuẩn HTTP chỉ định “unauthorized” (không có thẩm quyền), nhưng nó có nghĩa phản hồi này là “unauthenticated” (chưa được xác thực). Có nghĩa là, client phải các tự xác thực chính mình để nhận được phản hồi đã yêu cầu.

– 402 Payment Required: Code phản hồi này được dành cho những lần sử dụng trong tương lai. Mục đích ban đầu của việc tạo mã này là sử dụng nó cho các hệ thống thanh toán kỹ thuật số, tuy nhiên status code này rất hiếm khi được sử dụng và không tồn tại quy ước tiêu chuẩn nào.

– 403 Forbidden: Client không có quyền truy cập vào phần nội dung, nghĩa là nó không được phép, vì vậy máy chủ từ chối cung cấp tài nguyên được yêu cầu. Không giống như 401, danh tính của client đã được máy chủ nhận biết.

– 404 Not Found:

– 405 Method Not Allowed: Phương thức yêu cầu được máy chủ nhận biết nhưng đã bị vô hiệu hóa và không thể sử dụng được. Ví dụ: 1 API có thể cấm XÓA 1 nguồn tài nguyên. 2 phương thức bắt buộc, GET và HEAD, không bao giờ được vô hiệu hóa và không được trả về code lỗi này.

– 406 Not Acceptable: Phản hồi này được gửi khi máy chủ web, sau khi thực hiện server-driven content negotiation, không tìm thấy bất kỳ nội dung nào phù hợp với các tiêu chí do user-agent đưa ra.

– 407 Proxy Authentication Required: Code này tương tự như 401 nhưng việc xác thực là cần thiết để được thực hiện bởi proxy.

– 408 Request Timeout: Phản hồi này được gửi trên 1 kết nối idle bởi 1 số máy chủ, ngay cả khi không có bất kỳ yêu cầu nào trước đó của client. Có nghĩa là máy chủ muốn tắt kết nối không sử dụng này. Phản hồi này được sử dụng nhiều hơn vì 1 số trình duyệt như Chrome, Firefox 27+ hoặc IE9, sử dụng cơ chế tiền kết nối HTTP để tăng tốc độ lướt web. Cũng lưu ý rằng 1 số máy chủ chỉ tắt kết nối luôn mà không hề gửi thông báo này.

– 409 Conflict: Phản hồi này được gửi khi 1 yêu cầu xung đột với trạng thái hiện tại của máy chủ.

– 410 Gone: Phản hồi này được gửi khi nội dung được yêu cầu đã bị xóa vĩnh viễn khỏi máy chủ, không có địa chỉ chuyển tiếp. Client phải xóa bộ nhớ cache và liên kết của mình tới nguồn tài nguyên. HTTP spectication dự định status code này được sử dụng cho “các dịch vụ khuyến mại, có thời hạn”. Các API không nên bắt buộc phải chỉ ra các tài nguyên đã bị xóa bằng status code này.

– 411 Length Required: Máy chủ đã từ chối yêu cầu vì trường header Content-Lenghth không được xác định và máy chủ thì yêu cầu chuyện đó.

– 412 Precondition Failed: Client đã chỉ ra các điều kiện tiên quyết trong các header của nó mà máy chủ không đáp ứng được.

– 413 Payload Too Large: Thực thể yêu cầu lớn hơn giới hạn do máy chủ xác định, máy chủ có thể đóng kết nối hoặc trả về trường header Retry-After.

– 414 URI Too Long: URI được yêu cầu bởi client dài hơn mức máy chủ muốn thông dịch.

– 415 Unsupported Media Type: Định dạng phương tiện của dữ liệu được yêu cầu không được máy chủ hỗ trợ, do đó máy chủ đang từ chối yêu cầu.

– 416 Range Not Satisfiable: Client yêu cầu một phần của tập tin nhưng máy chủ không thể cung cấp nó. Trước đây được gọi là “Requested Range Not Satisfiable”.

– 417 Expectation Failed: Máy chủ không thể đáp ứng các yêu cầu của trường Expect trong header.

Server errors / Lỗi phía máy chủ:

– 500 Internal Server Error: Một thông báo chung, được đưa ra khi máy chủ gặp phải một trường hợp bất ngờ, message cụ thể không phù hợp.

– 501 Not Implemented: Máy chủ không công nhận các phương thức yêu cầu hoặc không có khả năng xử lý nó.

– 502 Bad Gateway: Máy chủ đã hoạt động như một gateway hoặc proxy và nhận được một phản hồi không hợp lệ từ máy chủ nguồn.

– 503 Service Unavailable: Máy chủ hiện tại không có sẵn (hiện đang quá tải hoặc bị down để bảo trì). Đây chỉ là trạng thái tạm thời.

– 504 Gateway Timeout: Máy chủ đã hoạt động như một gateway hoặc proxy và không nhận được một phản hồi từ máy chủ nguồn.

– 505 HTTP Version Not Supported: Máy chủ không hỗ trợ phiên bản “giao thức HTTP”.

Danh sách được tổng hợp và tham khảo từ Wikipedia & Mozilla.

  • Trending Categories
  • Data Structure
  • Networking
  • RDBMS
  • Operating System
  • Java
  • MS Excel
  • iOS
  • HTML
  • CSS
  • Android
  • Python
  • C Programming
  • C++
  • C#
  • MongoDB
  • MySQL
  • Javascript
  • PHP
  • Physics
  • Chemistry
  • Biology
  • Mathematics
  • English
  • Economics
  • Psychology
  • Social Studies
  • Fashion Studies
  • Legal Studies
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer’s Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

How to Send HTTP Response Code in PHP

PHP: PHP (Hypertext Preprocessor) is a popular server-side scripting language primarily used for web development. It was created by Rasmus Lerdorf in the mid-1990s and has since become one of the most widely used programming languages for building dynamic websites and web applications.

PHP is embedded within HTML code and executed on the server, generating dynamic web content that is then sent to the user’s web browser. It can interact with databases, handle form data, generate dynamic page content, perform calculations, manipulate files, and much more.

In PHP, there are multiple ways to send an HTTP response code. Here are four commonly used methods:

  • Using http_response_code() function

  • Using the header() function

  • Using the http_response_code header with header() function

  • Using the Response class in a PHP framework

Sending OTP SMS in PHP from localhost using textlocal
Sending OTP SMS in PHP from localhost using textlocal

Using http_response_code() function

Using the http_response_code() function is one of the methods to send an HTTP response code in PHP. Here’s how you can use it:

In this example, the http_response_code() function is used to set the HTTP response code to 200 (OK). The function sets the HTTP response code for the current request.

You can pass any valid HTTP response code as the parameter to http_response_code(). For example, 404 for Not Found, 500 for Internal Server Error, 301 for Redirect, etc.

Here’s an example of sending a 404 (Not Found) response code:

The http_response_code() function is available in PHP 5.4 and later versions. It is a convenient and straightforward way to set the response code without explicitly using the header() function.

It’s important to note that once you set the HTTP response code using http_response_code(), it becomes part of the response headers. Therefore, it should be called before any output is sent to the client. If you try to set the response code after output has already been sent, it may result in an error.

Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is essential for proper communication between the server and the client.

What is the `header()` Function?

The

header()

function is a built-in PHP function that allows you to send raw HTTP headers to the client. It is commonly used to set the Content-Type, redirect users, and send HTTP status codes. The syntax for the

header()

function is as follows:


header(string $header, bool $replace = true, int $http_response_code = 0)

Here are the function parameters:

  • $header: The header string to send.
  • $replace: (Optional) Indicates whether the header should replace the previously set header with the same name. If set to

    false

    , the new header will be added alongside any existing headers with the same name. The default value is

    true

    .
  • $http_response_code: (Optional) Forces the HTTP response code to the specified value. The default value is , which means the response code is not modified.
PHP REST API CRUD 1: Create API in PHP to fetch data from database in php mysql | Database & Read
PHP REST API CRUD 1: Create API in PHP to fetch data from database in php mysql | Database & Read

Why use PHP to generate status codes?

PHP is the language that WordPress is built on. If you are thinking of adapting your WordPress theme, or even writing additional pages using PHP, you might want to use status codes to return a positive status code, to redirect the request to another page or site, or to advise that a page is not available. For example, you have deleted a lot of content and you want to provide a special landing page to tell robots and users that this specific content has been removed, and why. Or, you may want to write a simple PHP script to tell users when the site is under maintenance.

PHP HTTP Response: Summary

  • When a client sends a request for certain information to the server, it provides it by sending a PHP HTTP response.
  • Before HTTP data that your browser sends to the server is outputted, you can modify it using HTTP PHP functions.
  • There’s no need to install these functions separately.

PHP http_response_code() Function

Example

Set the HTTP response status code to 404:


http_response_code(404);?>

http_response_code(404);

?>

Website quản lý bán hàng PHP & MySQL (Code thuần 100%)
Website quản lý bán hàng PHP & MySQL (Code thuần 100%)

Keywords searched by users: http status code php

Github - Josantonius/Php-Http-Status-Code: Php Library To Get Http Status  Code Definitions
Github – Josantonius/Php-Http-Status-Code: Php Library To Get Http Status Code Definitions
List Of Http Status Codes - Ryte Wiki
List Of Http Status Codes – Ryte Wiki
Http Response Status Codes
Http Response Status Codes
How To Correctly Return The Http Status Code 404 For An Error Page - Sistrix
How To Correctly Return The Http Status Code 404 For An Error Page – Sistrix
Http Status Codes Explained | Quattr Blog
Http Status Codes Explained | Quattr Blog
Php Rest Api #4 จัดการ Response Http Status Code - Youtube
Php Rest Api #4 จัดการ Response Http Status Code – Youtube
Tìm Hiểu Về Http Status Code - Viblo
Tìm Hiểu Về Http Status Code – Viblo
Http Status Codes - Javatpoint
Http Status Codes – Javatpoint
I Get A Null Response In My Php - Monday Apps & Developers - Monday  Community Forum
I Get A Null Response In My Php – Monday Apps & Developers – Monday Community Forum
Php Rest Api #4 จัดการ Response Http Status Code - Youtube
Php Rest Api #4 จัดการ Response Http Status Code – Youtube
Get Http Status Code From The Response · Issue #470 · Php-Webdriver/Php-Webdriver  · Github
Get Http Status Code From The Response · Issue #470 · Php-Webdriver/Php-Webdriver · Github
Which Http Status Code Should Use For Get, Post,Put, Delete,Patch Method |  204 For No Content - Youtube
Which Http Status Code Should Use For Get, Post,Put, Delete,Patch Method | 204 For No Content – Youtube

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *