What are some best practices for saving images from external sources in PHP?

When saving images from external sources in PHP, it is important to validate the image URL, download the image file, and save it to a secure location on your server. Additionally, it is recommended to sanitize the file name to prevent any potential security vulnerabilities.

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

// Download the image file
$image_data = file_get_contents($image_url);

// Save the image to a secure location on the server
$save_path = 'images/';
$file_name = basename($image_url);
$save_file = $save_path . $file_name;
file_put_contents($save_file, $image_data);