PHP header

The header() function sends a raw HTTP header to a client. The PHP header() function does not return any value.

Note : The header() function must be called before sending any actual output, normal HTML tags, blank lines in a file

PHP Syntax:

header($header, $replace, $http_response_code);

Where,
$header - Specifies the header string to send
$replace - This parameter is used for specifying whether a previous same header should be replaced by the header or add another header of same type. The $replace is a boolean type optional parameter. The default value is TRUE, which means that it replaces the previous same header. But you can bind several headers of same type if FALSE is passed as second argument.
$http_response_code - Send the HTTP response code to the specified value.

PHP header() function to redirect page to another location

PHP Syntax:

header('Location: $link');

PHP Example :
<?php  
        // Current page will be redirected to  new location https://www.aryatechno.com.
        header('Location: https://www.aryatechno.com/');  
        exit;  
?>

Output :
Current page will be redirected to new location https://www.aryatechno.com

PHP header() function to specify Redirection interval

PHP Syntax:

header('Refresh: time; url = $link');

PHP Example :
<?php  
        // Current page will be redirected to new location https://www.aryatechno.com after 20 seconds.
        header(Refresh: 20; url =https://www.aryatechno.com/');  
        exit;  
?>

Output :
Current page will be redirected to new location https://www.aryatechno.com after 20 seconds.

PHP header() function to specify Cache page

It prevents page caching.

Page contents must not be cached by the client browser as per as below.

<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 12 Aug 1976 06:20:00 GMT"); // Date in the past
?>

PHP header() function to Download file.

<?php
header('Content-Type: application/pdf');

header('Content-Disposition: attachment; filename="download_file.pdf"'); // Specify file name to save in your device.

readfile('original_file.pdf'); // Specify original file name which you want to download
?>

PHP header() function to send HTTP status code to the browser.

<?php
header("HTTP/1.0 404 Not Found");
?>

Above example send http status code 404. page is not found.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

92773