header() gửi header HTTP gốc đến client/trình duyệt trước mọi output. Dùng để điều khiển hành vi trình duyệt.
Các trường hợp dùng phổ biến
1. Chuyển hướng trang (Redirect)
header('Location: https://example.com');
2. Thiết lập Content-Type
// JSON
header('Content-Type: application/json');
// PDF
header('Content-Type: application/pdf');
3. Thiết lập HTTP Status Code
header("HTTP/1.0 404 Not Found");
4. Vô hiệu hóa cache
header("Cache-Control: no-cache, must-revalidate");
Lưu ý quan trọng
- Gọi
header()trước bất kỳ output nào (echo, khoảng trắng, HTML...). - Dùng
exit()sau redirect để dừng script.