Image headers with PHPImage 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:

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.

Comments

blog comments powered by Disqus