Home >Backend Development >PHP Tutorial >How to Display Images in PHP Using `header()` and `readfile()`?

How to Display Images in PHP Using `header()` and `readfile()`?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 12:43:12466browse

How to Display Images in PHP Using `header()` and `readfile()`?

Displaying Images in PHP

When working with images in PHP, it's often necessary to output them to the browser for display. This can be achieved by leveraging the header() and readfile() functions.

To output an image, first set the correct Content-Type and Content-Length headers, specifying the image's MIME type and file size. The Content-Type header informs the browser about the type of data being sent, while the Content-Length header specifies the size of the data in bytes.

header('Content-Type: ' . $type);
header('Content-Length: ' . filesize($file));

Replace $type with the MIME type of the image, and $file with the path to the image file on the server. For example:

header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize('../image.jpg'));

Finally, use the readfile() function to read the image data from the file and output it to the browser.

readfile($file);

This will send the image data directly to the browser, which will render it for display.

Sample Code:

$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type: ' . $type);
header('Content-Length: ' . filesize($file));
readfile($file);

The above is the detailed content of How to Display Images in PHP Using `header()` and `readfile()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn