PHP - header
Trieda
Metóda - header
The header() function is used for sending the HTTP header.
Warning:
- The function has to be called before any output is printed (even
white-spaces before
<?phpmay cause a problem). To prevent these problems you should use output buffering. - The function doesn't terminate the script execution, so if it's necessary
(e.g. while using redirection), you have to terminate it manually (using e.g.
exit).
Procedurálne
- function header (string $string, bool $replace = true, int $http_response_code) : void
Parametre
| Názov | Dátový typ | Predvolená hodnota | Popis |
|---|---|---|---|
| $string | string | The header string. 1. Setting the HTTP header Used to set the status code. For example, if you select an article from your database according to the given URL address and the user would provide an address that doesn't exists, you should display an error page and send a status code indicating that the page was not found. You'll avoid issues with wrong content indexation. <?php header("HTTP/1.0 404 Not Found"); 2. Redirection Used to redirect to an another page. If either status code 201 or 3xx hasn't been set, the 302 status code (found) is returned instead. Warning: Redirection won't stop the code execution, you have to terminate it manually. <?php header("Location: https://www.ict.social/"); exit; | |
| $replace | bool | true | Indicates, whether the value of an existing header with the same type should
be replaced or a new header with the same type should be added instead. The
default value <?php header('WWW-Authenticate: Negotiate'); header('WWW-Authenticate: NTLM', false); |
| $http_response_code | int | Forces the response code of the HTTP header to be the provided value. In case that no header was provided, this parameter has no effect. |
Mávratovej hodnoty
No return value is returned.
Príklady
Setting an error 404 header:
<?php header('HTTP/1.0 404 Not Found');
Redirecting to https://www.itnetwork.cz/ with code 301 (moved permanently):
<?php header('Location: https://www.itnetwork.cz/', true, 301);
Setting the content type of a current response:
<?php header('Content-type: application/pdf');
Disabling browser cache:
<?php header('Expires: Thu, 1 Jan 1997 01:00:00 GMT'); header('Cache-Control: no-cache'); header('Pragma: no-cache');
HTTP authentication:
<?php header('WWW-Authenticate: Basic realm=""'); header('HTTP/1.0 401 Unauthorized');
Wrong: Printing the text before setting up the header:
<?php
echo('Text');
header('HTTP/1.0 404 Not Found');
Correct: Printing the text before setting up the header using a buffer:
<?php
ob_start();
echo('Text');
header('HTTP/1.0 404 Not Found');
$buffer = ob_get_clean();
echo($buffer);
