Home > Backend Development > PHP Tutorial > How to Output an Image in PHP?

How to Output an Image in PHP?

Linda Hamilton
Release: 2024-12-08 11:01:11
Original
228 people have browsed it

How to Output an Image in PHP?

Outputting an Image in PHP

In PHP, displaying an image in a web browser involves sending the image data along with appropriate headers. To achieve this, you can follow these steps:

1. Determine the Image File and MIME Type:

  • Assign the path to the image file to the $file variable (e.g., '../image.jpg').
  • Specify the MIME type of the image (e.g., 'image/jpeg') in the $type variable.

2. Send Content Headers:

  • header('Content-Type:'.$type); sets the MIME type to indicate the type of data being output.
  • header('Content-Length: ' . filesize($file)); specifies the size of the file being sent.

3. Read and Output the Image Data:

  • readfile($file); reads the content of the image file and sends it to the output buffer.

Example:

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

By using this code, you can output an image directly to the browser, allowing it to be displayed on the web page.

The above is the detailed content of How to Output an Image in PHP?. 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