How to Send a PHP Image File

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.

Video of the Day


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".

<? $img_data = file_get_contents("images/phpimage.png"); ?>


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".

<? $img_data = file_get_contents("images/phpimage.png"); header("Content-type: image/png"); ?>


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

<? $img_data = file_get_contents("images/phpimage.png"); header("Content-type: image/png"); echo $img_data; ?>

Show Comments