Sunday, 18 August 2019

Examples of the PHP Header Function


The PHP header() function allows us send a HTML header to a client. We can specify the header string in the function for a redirect, displaying files and preventing page caching.


The following code snippet makes a redirect to an external website.

    $url = '';
    header('Location: ' . $url);

If we want redirect to a file in another path, we can specify the path and the file for the header 'Location' as belows:

    $url = 'path/myfile.php';
    header('Location: ' . $url);

Displaying files

For displaying a PDF file inline in a browser, we can send following headers.

    $pdfName = 'myfile.pdf';
    header('Content-type: application/pdf');
    header('Content-Disposition: inline; filename="' . $pdfName . '"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($pdfName));
    header('Accept-Ranges: bytes');

Line 4 defines inline in the 'Content-Disposition' header that requests the client browser open the PDF file inline. If we want to prompt a download dialog for the file, we can define it as attachment in line 4.

header('Content-Disposition: attachment; filename="' . $pdfName . '"');

For displaying image files, we need change the 'Content-type' header regarding different image types: header('Content-type: image/png'); is for PNG, header('Content-type: image/jpeg'); is for JPEG and header('Content-type: image/bmp'); is for BMP.

Preventing page caching

In the code snippet below, we define the header 'Expires' in line 2 as a date in the past to request the browser to get the resource again. Line 4 is the 'Pragma' header for backwards compatibility with HTTP/1.0 clients for turning cache off.

    header('Expires: 01 Jan 1901 00:00:00 GMT');
    header('Cache-Control: no-cache');
    header('Pragma: no-cache');