Displaying Images Retrieved with file_get_contents in PHP
In PHP, you can retrieve remote images using the file_get_contents function. However, to display these images on a web page, you need to take additional steps.
Solution:
You can use PHP's readfile() function to output the image directly to the browser. Before doing this, you need to set the correct image headers using getimagesize().
<code class="php"><?php $remoteImage = "http://www.example.com/gifs/logo.gif"; // Get image information $imginfo = getimagesize($remoteImage); // Set image headers header("Content-type: {$imginfo['mime']}"); // Output the image to the browser readfile($remoteImage); ?></code>
Explanation:
getimagesize() retrieves the image's size and mime type.
header() sets the necessary image headers, such as the Content-type, which specifies the image's type (e.g., "image/gif").
readfile() outputs the image directly to the output buffer, reducing memory consumption compared to using file_get_contents.
The above is the detailed content of How to Display Images Retrieved with `file_get_contents` in PHP?. For more information, please follow other related articles on the PHP Chinese website!