header() dùng để gửi 1 HTTP header thô tới trình duyệt. HTTP headers được mô tả chi tiết trong HTTP/1.1
header
(PHP 4, PHP 5)
header — Send a raw HTTP header
Description
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
?>
Parameters
- string
-
The header string.
There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.
<?php
header("HTTP/1.0 404 Not Found");
?>The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless some 3xx status code has already been set.
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?> - replace
-
The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:
<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?> - http_response_code
-
Forces the HTTP response code to the specified value.
Return Values
No value is returned.
Changelog
| Version | Description |
|---|---|
| 4.4.2 and 5.1.2 | This function now prevents more than one header to be sent at once as a protection against header injection attacks. |
| 4.3.0 | The http_response_code parameter was added. |
| 4.0.4 | The replace parameter was added. |
Examples
Example #1 Download dialog
If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
Example #2 Caching directives
PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with:
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>
Note: You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.
Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.
Notes
Note: As of PHP 4, you can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.
Note: The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.
Note: There is a bug in Microsoft Internet Explorer 4.01 that prevents this from working. There is no workaround. There is also a bug in Microsoft Internet Explorer 5.5 that interferes with this, which can be resolved by upgrading to Service Pack 2 or later.
Note: If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).
Note: HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:
<?php
/* Redirect to a different page in the current directory that was requested */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>
Note: Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.
See Also
- headers_sent() - Checks if or where headers have been sent
- setcookie() - Send a cookie
- The section on HTTP authentication
header
06-Jun-2009 09:23
In response to Alex regarding header('content-type:text/css');
Safari seems to need more:
header(”Content-Type: text/css; charset: utf-8″);
See Safari and php generated css at http://blog.strugglewith.me.uk/?p=16 17-May-2009 07:38
The loaction header must contain an absolute URI!!
See note above "Note: HTTP/1.1 requires an absolute URI as argument to » Location".
Thus:
<?php header("Location: /home.php"); ?>
is wrong, but most browsers will follow it correctly (hence the common mistake).
This is correct:
<?php
header("Status: 301"); # 301 Moved Permanently
header("Location: http://{$_SERVER['SERVER_NAME']}/home.php");
exit;
?> 03-Apr-2009 08:40
I've just discovered that Chrome doesn't perform a Location: instruction unless it gets a Status: first. It's also sensitive to capitalisation.
<?php
header("Status: 200");
header("Location: /home.php");
exit;
?> | Lập trình PHP - Mã hóa file bằng md5 < Lùi | Tiếp theo > Lập trình PHP, MySQL - Tạo trang đăng nhập Login |
|---|
- 28/06/2009 21:15 - Viết chương trình download manager đơn giản
- 10/06/2009 16:00 - Lập trình PHP - Đếm số người trực tuyến
- 09/06/2009 23:50 - Chuỗi (xâu) và các hàm xử lý chuỗi trong PHP
- 09/06/2009 16:53 - Hàm PHP: substr_compare
- 08/06/2009 22:24 - Lập trình PHP - Mã hóa file bằng md5
- 03/06/2009 23:50 - Lập trình PHP, MySQL - Tạo trang đăng nhập Login
- 03/06/2009 22:00 - Lập trình PHP - Tạo 1 shoutbox đơn giản
- 03/06/2009 18:24 - Chuyển hướng Redirection với Drop Down Menu
- 02/06/2009 18:02 - Class: PHP Ajax Voting system
- 09/05/2009 15:02 - Xây dựng lớp Cắt xâu HTML string trong Lập trình PHP
Download Game bóng đá PES8 Việt Nam
Tải game bóng đá FiFa 09
Tải game Dragon ball Z - 7 viên ngọc rồng
Tải Game Bóng Đá Pro Evolution Soccer 6 Việt Nam
Download PES 2011 patch Việt Nam PESVN
Tải Game Bóng Đá FIFA 2009 RIP 1 CD
Download Pro Evolution Soccer 2011
Download Game THE SIMS 3
Tải Game bóng đá PES 2009
Download PES 2011 demo
Thay đổi màn hình đăng nhập Windows 7 bằng tay
Một số hàm hay dùng trong JavaScript
Kiểm soát hoàn toàn trỏ chuột bằng bàn phím với NeatMouse
Choáng với concept của Windows Phone 8
Những đặc điểm ưu việt của Windows Phone
Ứng dụng gọi điện VoIP Viber sắp có mặt trên Windows Phone
Game Diablo 3 sắp có mặt trên Windows Phone Marketplace
37 trang css & xhtml web template miễn phí tuyệt đẹp
Những điều cơ bản cần biết về bàn phím chơi game - Gaming Keyboard
L.A. Noire: The Complete Edition - THETA [Full ISO/Action/2011] [13.37GB]
Download 7554 demo
Download Game PC, cập nhật liên tục (torrent)
PES 2012 ra mắt bản mở rộng đầu tiên vào 11/10
PES2012 - Full version - Ngôn ngữ và bình luận tiếng Anh
PES2012 - Blurry disable làm mịn đồ họa
PES 2011 PATCH 4.1 - TRANSFER UPDATE - RELEASED
Bộ sưu tập free PrestaShop Themes phần 3
Bộ sưu tập theme Prestashop miễn phí phần 2
Top 10 Free PrestaShop Themes
Download Prestashop 1.5
Download PrestaShop 1.4
Bổ sung Memcached vào PrestaShop 1.4
Hướng dẫn tích hợp Ngân Lượng vào PrestaShop
Sửa lỗi invalid carrier or no carrier selected trong PrestaShop
Cài đặt PrestaShop
Thiết kế giao diện PrestaShop Theme
Hướng dẫn cài đặt themes trong PrestaShop
Hướng dẫn cách thêm ngôn ngữ cho PrestaShop
Bộ sưu tập Giao diện Premium PrestaShop Themes chuyên nghiệp
Giới thiệu về website thương mại điện tử 2.0 Prestashop
10 smartphone “bom xịt” năm 2010
Pro Evolution Soccer 2010 - Sự trở lại của vị vua [RELOADED][PC Game]
Bài 1: Làm quen với hệ quản trị cơ sở dữ liệu Microsoft Access


