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:
- 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)
Recent posts:
- MySQL queries for article summaries part 2 of 2 (Tuesday, January 6th 2009)
- Aims for 2009 (Monday, January 5th 2009)
- Weekly Roundup - January 5th 2008 (Monday, January 5th 2009)
- MySQL queries for article summaries part 1 of 2 (Sunday, January 4th 2009)
- 2008 Summary of Posts (Saturday, January 3rd 2009)
- 2008 / 2009 overview (Friday, January 2nd 2009)
Subscribe to RSS Feed / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email and have my posts sent in a daily email.
Posts are made using the following schedule (although it may vary some weeks): Mondays & Fridays = PHP; Tuesdays & Saturdays = MySQL; Wednesdays & Sundays = Javascript/jQuery; Thursdays = HTML/CSS.
