What are best practices for handling image files retrieved from URLs in PHP?
When handling image files retrieved from URLs in PHP, it is important to validate the file type, download the image securely, and save it to a local directory. One way to achieve this is by using the `file_get_contents()` function to retrieve the image data and `file_put_contents()` function to save it locally.
$url = 'https://example.com/image.jpg';
$localPath = 'images/image.jpg';
if (filter_var($url, FILTER_VALIDATE_URL) && pathinfo($url, PATHINFO_EXTENSION) == 'jpg') {
$imageData = file_get_contents($url);
if ($imageData !== false) {
file_put_contents($localPath, $imageData);
echo 'Image downloaded successfully.';
} else {
echo 'Failed to download image.';
}
} else {
echo 'Invalid image URL.';
}