The key is the code starting from ob_end_clean();.

 // Read background image and target image
$backgroundPath = 'background_image_path';
$overlayPath = 'overlay_image_path';

// Get resources of background image and target image
$background = imagecreatefrompng($backgroundPath);
$overlay = imagecreatefrompng($overlayPath);

// Get the width and height of the target image
$overlayWidth = imagesx($overlay);
$overlayHeight = imagesy($overlay);

// Overlay the target image onto the background image
imagecopy($background, $overlay, 0, 0, 0, 0, $overlayWidth, $overlayHeight);

// Create a new image resource
$output = imagecreatetruecolor($overlayWidth, $overlayHeight);

// Copy the overlaid image to the output image
imagecopy($output, $background, 0, 0, 0, 0, $overlayWidth, $overlayHeight);

ob_end_clean();
header("content-type:image/png");
ob_start();
imagejpeg($output);
$content = ob_get_contents();
ob_end_clean();
echo $content;
die;