O'Reilly logo

PHP in a Nutshell by Paul Hudson

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

Outputting Text

To output text using PHP, you first need fonts. PHP allows you to use TrueType (TTF) fonts, PostScript Type 1 (PS) fonts, or FreeType 2 fonts, with TTF tending to be the most popular, due to the availability of fonts. If you are running Windows, you probably have at least 20 TTF fonts already installed that you can use—check in the "Fonts" subdirectory of your Windows directory to see what is available. Many Unix distributions come with TTF fonts installed also—either check in /usr/share/fonts/truetype, or run a search for them. Alternatively, if you have a Windows CD around, you can borrow some from there. Some distributions (including Debian and SUSE) allow you to install Microsoft's Core Fonts for the Web. The Free Software Foundation has a set of free fonts that you can grab from its web site.

For this next example, I used the font Arial, which is stored in the same directory as my PHP script. Save this code as addingtext.php:

    $image = imagecreate(400,300);
    $blue = imagecolorallocate($image, 0, 0, 255);
    $white = ImageColorAllocate($image, 255,255,255);

    if(!isset($_GET['size'])) $_GET['size'] = 44;
    if(!isset($_GET['text'])) $_GET['text'] = "Hello, world!";

    imagettftext($image, $_GET['size'], 15, 50, 200, $white,
            "ARIAL", $_GET['text']);
    header("content-type: image/png");
    imagepng($image);
    imagedestroy($image);

The two isset() lines in that example are there to make sure there is a default font size, 44, and default text, "Hello, world!" for our image. These are ...

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