How can PHP be used to generate and display images, such as bar charts, in a web application?

To generate and display images like bar charts in a web application using PHP, you can utilize libraries such as GD or Imagick to create the image dynamically based on data inputs. These libraries allow you to draw shapes, text, and colors on a blank canvas to generate the desired chart. Once the image is created, you can output it to the browser using appropriate headers to specify the image type.

<?php
// Create a blank image
$image = imagecreate(400, 300);

// Set background color
$bg_color = imagecolorallocate($image, 255, 255, 255);

// Set bar color
$bar_color = imagecolorallocate($image, 0, 0, 255);

// Draw a bar chart
$data = [20, 40, 60, 80];
$bar_width = 50;
$spacing = 20;
$x = 50;
foreach ($data as $value) {
    imagefilledrectangle($image, $x, 300 - $value, $x + $bar_width, 300, $bar_color);
    $x += $bar_width + $spacing;
}

// Set header and output image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>