Are there any potential security risks associated with saving images from external URLs to a server using PHP?

When saving images from external URLs to a server using PHP, there are potential security risks such as malicious code injection or file upload vulnerabilities. To mitigate these risks, it is important to validate the image URL, sanitize the file name, and ensure that the file is an actual image before saving it to the server.

<?php
// Validate the image URL
$image_url = 'https://example.com/image.jpg';
if (filter_var($image_url, FILTER_VALIDATE_URL) === false) {
    die('Invalid image URL');
}

// Sanitize the file name
$file_name = basename($image_url);
$file_name = preg_replace('/[^A-Za-z0-9\_\-\.]/', '', $file_name);

// Check if the file is an actual image
$image_info = getimagesize($image_url);
if ($image_info === false) {
    die('Invalid image file');
}

// Save the image to the server
$image_data = file_get_contents($image_url);
file_put_contents('images/' . $file_name, $image_data);
?>