Programming Languages
PHP
Subjective
Nov 23, 2012
In PHP, header () function is used for what?
Detailed Explanation
The header() function sends raw HTTP headers to the client browser.
Common Use Cases:
// 1. Page Redirection
header("Location: https://example.com/dashboard");
exit(); // Always use exit after redirect
// 2. Set Content Type
header("Content-Type: application/json");
echo json_encode(["status" => "success"]);
// 3. Force File Download
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"report.pdf\"");
header("Content-Length: " . filesize("report.pdf"));
readfile("report.pdf");
// 4. Cache Control
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
// 5. HTTP Status Codes
header("HTTP/1.1 404 Not Found");
header("HTTP/1.1 500 Internal Server Error");
Security Headers:
// CORS headers
header("Access-Control-Allow-Origin: https://trusted-site.com");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
// Security headers
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");
header("Strict-Transport-Security: max-age=31536000");
// Content Security Policy
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'");
Important Notes:
- Must be called before any output (HTML, echo, print)
- Use exit() after redirect headers
- Headers are case-insensitive
- Can be overwritten by calling header() again
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts