What security measures should be implemented when allowing live text input for image generation in PHP to prevent vulnerabilities?

When allowing live text input for image generation in PHP, it is important to implement security measures to prevent vulnerabilities such as code injection or XSS attacks. One way to do this is by sanitizing the input data to remove any potentially harmful characters or scripts before using it to generate the image.

// Sanitize the text input before using it for image generation
$text = htmlspecialchars($_POST['text']);

// Generate the image using the sanitized text
$im = imagecreate(200, 50);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 5, 10, 10, $text, $black);

// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);