Image Output - Dynamically Coloured Squares

We can adapt the previous script to be a little more dynamic. PHP allows us to pass values through URLs or by submitting form data with the POST method. We can use information supplied at run time to allow the same script to produce different images.

In this example, we will use a similar simple shape but add some text supplied via the GET method.

header("Content-Type: image/png");
$im = @imagecreate(100, 100);
$green = imagecolorallocate($im, 0, 255, 0);
$red = imagecolorallocate($im, 255, 0, 0);
imagefilledrectangle($im, 0, 0, 99, 99, $green);
if (isset($_GET['txt']))
   $thetext = $_GET['txt'];
   imagestring($im, 5, 10, 40, $thetext, $red);

You can see this image in a similar way to the previous script. Either type in the URL and add a query string,


or, alternatively, you use this URL as the src for an HTML image,

<img src='square.php?txt=shut_up' alt='image drawn dynamically'>

Image library documentation can be found at Use the documentation to make some alterations to the script. Go wild and change the shape, the size or positioning of the text.

With a couple of short PHP scripts, you should be able to create a page of images like this,

Square Pattern

You should be able to do this with one PHP file to produce the images - adding the number based on the value of the GET variable. The script that contains the images needs a for loop counting from 1 to your end number. To break a line after every nth image, use the modulus operator (%) to determine whether the iteration number is exactly divisible by your line-break interval.