Contents Previous Next

## 4.2 How to generate images with PHP

As a general rule each PHP script which generates an image must be specified in a separate file which is then called in an HTML <IMG> tag. For example, the following HTML excerpt includes the image generated by the PHP script in "fig1.php".

`<img src="fig1.php" border=0 align=center width =300 height=200>`

Strictly speaking the "align", "width" and "height" are not necessary but helps the browser position the image correctly before the image has been fully sent back to the browser.

The library will automatically generate the necessary headers to be sent back to the browser so that it correctly recognize the data stream received as an image of either PNG/GIF/JPEG format. The browser can then correctly decode the image

Observe that you can't return anything else than an image from the image script. By definition each HTML page (or more correctly each HTTP stream) can only consist of one mime type which is determined by the header for that particular stream.

A common mistake is to have a space in the beginning of the image script which the HTTP server will send back to the browser. The browser now assumes that the data coming back from this script is text since it hasn't received an explicit header. When then the image headers get sent back to the browser to forewarn the browser of the forthcoming image the browser will not like that as it has already assumed the data stream was a text stream. The browser will then give the infamous "Headers already sent error".

To include several images together with text on a page you need to have a parent page with several <IMG> tags which each refers to an image script (or the same image script with GET/POST data).

Contents Previous Next