What are the potential security risks of saving an image from an external URL onto a local server in PHP?

Saving an image from an external URL onto a local server in PHP can pose security risks such as potential injection attacks or downloading malicious files. To mitigate these risks, it is important to validate the URL and ensure it is a safe image file before saving it locally.

// Validate the URL to ensure it is a safe image file
$url = 'https://example.com/image.jpg';
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
$extension = pathinfo($url, PATHINFO_EXTENSION);

if (in_array($extension, $allowed_extensions)) {
    // Download and save the image locally
    $image = file_get_contents($url);
    file_put_contents('local/image.jpg', $image);
    echo 'Image saved successfully.';
} else {
    echo 'Invalid image file format.';
}