What are some potential pitfalls when using file_get_contents to retrieve images from a URL in PHP?

One potential pitfall when using file_get_contents to retrieve images from a URL in PHP is that it may not handle large files efficiently, leading to memory exhaustion. To solve this issue, you can use the fopen function with a stream context to read the file in chunks and save it directly to a local file.

$url = 'https://example.com/image.jpg';
$localFile = 'image.jpg';

$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    ]
]);

if (($remoteFile = fopen($url, 'rb', false, $context)) !== false) {
    if (($localFile = fopen($localFile, 'wb')) !== false) {
        while (!feof($remoteFile)) {
            fwrite($localFile, fread($remoteFile, 8192));
        }
        fclose($localFile);
    }
    fclose($remoteFile);
}