How can one securely pass text data to be written on an image using GD in PHP, especially when using GET requests?

When passing text data to be written on an image using GD in PHP, especially with GET requests, it is important to properly sanitize and validate the input to prevent any security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to securely pass text data is to use PHP's htmlspecialchars() function to escape special characters and prevent code injection. Additionally, validating the input against a whitelist of allowed characters can add an extra layer of security.

// Sanitize and validate the text data passed via GET request
$text = isset($_GET['text']) ? htmlspecialchars($_GET['text']) : '';
$text = preg_replace('/[^A-Za-z0-9 ]/', '', $text); // Allow only alphanumeric characters and spaces

// Write the text on an image using GD
$im = imagecreatefrompng('image.png');
$black = imagecolorallocate($im, 0, 0, 0);
imagettftext($im, 20, 0, 10, 50, $black, 'arial.ttf', $text);

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