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.
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;?>
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 "" tag. Doing this will cause an error, as all HTTP headers must be sent prior to the body of the document.