Dynamic progress bar with PHP GD

by Lasantha Samarakoon on Wednesday, February 24, 2010

Today I’m going to show you something regarding GD library of PHP. The GD library is the main library using for Graphics in PHP. By using functions of this library, it is possible to manipulate images with PHP.

In this post, I will show you how to create a dynamic progress bar with PHP. In here the “dynamic” means you can parse 2 values, (i.e. maximum value and the current value) and the PHP script will calculate and render the progress bar dynamically on the screen. The output will come in the format of PNG image file. Hence it is very easy to use in you HTML file.

That’s all about the explanation. So let’s go for codes…

<?php
// filename: progressbar.php
// author  : lasantha samarakoon

// set the type of data (Content-Type) to PNG image
header("Content-Type: image/png");

// extract GET global array
extract($_GET);

// set defaults
if(! isset($max)) $max = 100;
if(! isset($val)) $val = 100;

// this method prepare blank true color image with given width and height
$im = imagecreatetruecolor(400, 20);

// set background color (light-blue)
$c_bg = imagecolorallocate($im, 222, 236, 247);
// set foreground color (dark-blue)
$c_fg = imagecolorallocate($im, 27, 120, 179);

// calculate the width of bar indicator
$val_w = round(($val * 397) / $max);

// create a rectangle for background and append to the image
imagefilledrectangle($im, 0, 0, 400, 20, $c_bg);
// create a rectangle for the indicator and appent to the image
imagefilledrectangle($im, 2, 2, $val_w, 17, $c_fg);

// render the image as a PNG
imagepng($im);

// finally destroy image resources
imagedestroy($im);
?>

OK… that is the PHP script. Now it’s time to display it in the browser. First create a HTML file to display the image. In the IMG tag of the HTML file, type the location of your PHP script and specify 2 values, maximum and current as follows.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Progress Bar</title>
</head>

<body>
 
    <img src="progressbar.php?max=100&val=70" />
 
</body>
</html>

That’s all, and you can see the output…

2 comments

Fantastic guide. Thank you.

by Anonymous on July 7, 2012 at 10:52 AM. #

Wow. Thanks.

by David on March 12, 2015 at 3:24 PM. #

Leave your comment