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
Release: 2024-12-07 12:43:12
Original
379 people have browsed it

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));
Copy after login

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'));
Copy after login

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

readfile($file);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template