NOVINKA: Najžiadanejšie rekvalifikačné kurzy teraz s 50% zľavou + kurz AI ZADARMO. Nečakaj, táto ponuka dlho nevydrží! Zisti viac:

PHP - header

Trieda

Koreň \ Bez triedy

Metóda - header

The header() function is used for sending the HTTP header.

Warning:

  1. The function has to be called before any output is printed (even white-spaces before <?php may cause a problem). To prevent these problems you should use output buffering.
  2. 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ázovDátový typPredvolená hodnotaPopis
$stringstring

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;
$replacebool 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 true means replacing the header. To add another header of the same type you have to pass false.

<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
$http_response_codeint

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

Vracia:

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);

Súvisiace manuály

        Aktivity