How to Send a PHP Image File

By Chris Davis

PHP is a powerful scripting language that is often used to create dynamic Web pages and applications. The functionality that PHP provides to a Web developer is virtually endless, allowing a programmer to present content to a user as well as modifying files and database entries on the server. While PHP files are most commonly used to send HTML pages to a Web browser, it can also be used to send other types of files, including images.

Step 1

Read the contents of the image file into a string variable. For this example, assume that the image file you will be sending is in a subdirectory called "images" and that the file is named "phpimage.png".

Step 2

Send an HTTP header telling the user's Web browser that the data you are sending is an image. Since the file you are sending is a PNG, the MIME (Multipurpose Internet Mail Extensions) type is "image/png". Some other common image MIMEs include "image/jpeg", "image/gif" and "image/tiff".

Step 3

Send the contents of the string variable to the user with an echo.

Tips & Warnings

  • You can expand this code to do things such as dynamically selecting from a number of images, reading the image data from a database instead of a file or displaying an error image if the file requested cannot be found.
  • Be sure not to send any data before the header command. A common mistake is to have a blank line above the initial "