What is the purpose of the header () function?
Just mount a header for the HTTP packet that will be transmitted on that request. By default it generates a basic with the minimum necessary, if you want to customize you can use this function.
Does the header () function have any relation to the HTTP protocol?
Totally, it only makes sense for this.
When should the header () function be used?
Whenever you need to do something that is not the ordinary. You can send a specific error ( HTTP/1.0 404 Not Found
), it 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');