Chapter 9. Graphics
The Web is more than just text. Images appear in the form of logos, buttons, photographs, charts, advertisements, and icons. Many of these images are static, built with tools such as PhotoShop and never changed. But many are dynamically created—from advertisements for Amazon's referral program that include your name to Yahoo! Finance's graphs of stock performance.
PHP supports graphics creation with the GD and Imlib2 extensions. In this chapter we'll show you how to generate images dynamically with PHP, using the GD extension.
9.1. Embedding an Image in a Page
A common misconception is that there is a mixture of text and graphics flowing across a single HTTP request. After all, when you view a page you see a single page containing such a mixture. It is important to understand that a standard web page containing text and graphics is created through a series of HTTP requests from the web browser, each answered by a response from the web server. Each response can contain one and only one type of data, and each image requires a separate HTTP request and web server response. Thus, if you see a page that contains some text and two images, you know that it has taken three HTTP requests and corresponding responses to construct this page.
Take this HTML page, for example:
<html> <head> <title>Example Page</title> </head> <body> This page contains two images. <img src="image1.jpg" alt="Image 1"> <img src="image2.jpg" alt="Image 2"> </body> </html>
The series of requests sent by the web browser for this page looks something like this:
GET /page.html HTTP/1.0 GET /image1.jpg HTTP/1.0 GET /image2.jpg HTTP/1.0
The web server sends back a response to each of these requests. The Content-Type headers in these responses look like this:
Content-Type: text/html Content-Type: image/jpeg Content-Type: image/jpeg
To embed a PHP-generated image in an HTML page, pretend that the PHP script that generates the image is actually the image. Thus, if we have image1.php and image2.php scripts that create images, we can modify the previous HTML to look like this:
<html> <head> <title>Example Page</title> </head> <body> This page contains two images. <img src="image1.php" alt="Image 1"> <img src="image2.php" alt="Image 2"> </body> </html>
Instead of referring to real images on your web server, the img tags now refer to the PHP scripts that generate the images.
Furthermore, you can pass variables to these scripts, so instead of having separate scripts to generate the two images, you could write your img tags like this:
<img src="image.php?num=1" alt="Image 1"> <img src="image.php?num=2" alt="Image 2">
Then, inside image.php, you can access $_GET['num'] (or $num, if register_globals is on) to generate the appropriate image.
Copyright © 2003 O'Reilly & Associates. All rights reserved.