Image headers with PHP
Posted July 22nd, 2008 in PHP
If you ever need to send an image file with PHP from the web server to the web browser you need to add an additional header using the header() function so the browser knows it's an image and not regular HTML. This post looks at the headers you need to use.
There are a variety of methods for creating and manipulating images with PHP, as well as simply opening the file and then sending the contents to the web browser. All of these methods require setting the Content-Type header to the image's mime type so the browser knows what sort of file type it is.
The following examples show doing this for GIF, JPEG and PNG images, and then use the readfile() function to pass through the content of the file to the web browser.
GIF:
header('Content-Type: image/gif');
readfile('path/to/myimage.gif');
JPEG:
header('Content-Type: image/jpeg');
readfile('path/to/myimage.jpg');
PNG:
header('Content-Type: image/png');
readfile('path/to/myimage.png');
You can use the same header functions for sending other mime types as well, for example when sending a PDF or Flash file to the browser.
Related posts:
- Apache does not log HTTP status set with PHP header when using mod_rewrite in .htaccess files (Sunday, April 5th 2009)
- RSS with PHP - Don't forget to set the Content-Type (Saturday, December 27th 2008)
- Set the content encoding type with PHP headers (Saturday, December 13th 2008)
- PHP fatal libpng error: zlib error (Tuesday, November 4th 2008)
- Get an image size with PHP (Wednesday, July 9th 2008)
- PHP error Call to undefined function ImageCreateFromPNG (Wednesday, January 9th 2008)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

