What is the purpose of the header function()?
Just mount a header for the HTTP package that will be transmitted in that request. By default it generates a basic with the minimum necessary, if you want to customize can use this function.
The header() function has some relation to the HTTP protocol?
Totally, it just makes sense.
When the header() function should be used?
Whenever you need to do something that is not common. You can send a specific error (HTTP/1.0 404 Not Found
), can indicate the type of content that will be sent (Content-Type
), expiration (Expires
), work with authentication (WWW-Authenticate: Basic realm="realm"
), and perhaps one of the most used in practice, redirect to other content (location
). But anything that allows the protocol can be used, even header extensions.
Documentation.
Examples:
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://www.example.com');
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 60');
header('Content-Type: image/png');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header ('Pragma: no-cache');
header('Content-Disposition: attachment; filename=' . urlencode($file));
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream');
header('Content-Type: application/download');
header('Content-Description: File Transfer');
header('Content-Length: ' . filesize($file));
echo file_get_contents($file);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="plain_text_file.txt"');
header('WWW-Authenticate: Basic realm="The Realm"');
header('HTTP/1.0 401 Unauthorized');
I put in the Github for future reference.
The Header of an HTTP request/response is a key/value list. Basically this function adds new values, or updates values that already exist in the response header.
– mau humor