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);
}
Keywords
Related Questions
- Are there any best practices or alternatives to consider when fetching data from a database in PHP to avoid overwriting arrays?
- Are there best practices for using QSA in RewriteRules for preserving original parameters in PHP URLs?
- Are there specific PHP functions or libraries that can be used to restrict the types of image formats allowed for upload?