O'Reilly logo

Programming PHP, 2nd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dynamically Generated Buttons

A popular use for dynamically generated images is to create images for buttons on the fly (this was introduced to you in Chapter 1 as well). Normally, a blank button background image is used and text is overlaid on top of it, as shown in Example 9-8.

Example 9-8. Creating a dynamic button

<?php
 $font = 'times';
 if (!$size) $size = 12;
 $im = ImageCreateFromPNG('button.png');
 // calculate position of text
 $tsize = ImageTTFBBox($size,0,$font,$text);
 $dx = abs($tsize[2]-$tsize[0]);
 $dy = abs($tsize[5]-$tsize[3]);
 $x = ( ImageSx($im) - $dx ) / 2;
 $y = ( ImageSy($im) - $dy ) / 2 + $dy;
 // draw text
 $black = ImageColorAllocate($im,0,0,0);
 ImageTTFText($im, $size, 0, $x, $y, $black, $font, $text);
 header('Content-Type: image/png');
 ImagePNG($im);
?>

In this case, the blank button (button.png) looks as shown in Figure 9-7.

Blank Button

Figure 9-7. Blank Button

The script in Example 9-8 can be called from a page like this:

<img src="button.php?text=PHP+Button">

This HTML generates the button shown in Figure 9-8.

Button with generated text label

Figure 9-8. Button with generated text label

The + character in the URL is the encoded form of a space. Spaces are illegal in URLs and must be encoded. Use PHP's urlencode( ) function to encode your button strings. For example:

<img src="button.php?text=<?php echo urlencode('PHP ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required