Main Content

Using PHP to output images, XML, Style sheets, etc

Archive - Originally posted on "The Horse's Mouth" - 2006-01-15 12:44:49 - Graham Ellis

PHP is usually used to generate a stream of HTML to be sent to the browser, but if you use the header function within your page you can use it to send any other type you wish. For example, if I include

header("Content-type: image/jpeg");

then I can script the production of images. Easy? Yes, but two words or caution:

a) The header call must be included within your script before it generates a single byte of output. Rephrasing that, the < character of the initial <?php must be on the very first line and in the very first column of your script, and not a single byte may be output until you've made the header call.

b) If you select a format such as jpeg to send out, it's your responsibility to ensure that it's a valid jpeg image stream. More often than not, you'll do this with the Gd library, but if you're using PHP simply to upload images and manage their storage, that's not necessary. We have an example script to upload, store and retrieve images in a database in our solution centre.