Displaying Images with file_get_contents
When retrieving an image using file_get_contents, you may encounter the need to display it in your PHP application. One efficient method to achieve this is through the use of the readfile function and header manipulation.
Solution
To display an image retrieved using file_get_contents, follow these steps:
Obtain the image information using getimagesize:
<code class="php">$remoteImage = "http://www.example.com/gifs/logo.gif"; $imginfo = getimagesize($remoteImage);</code>
Set the appropriate headers to indicate the file type:
<code class="php">header("Content-type: {$imginfo['mime']}");</code>
Output the image using readfile, which directly sends the content to the output buffer:
<code class="php">readfile($remoteImage);</code>
Rationale
Using readfile is more efficient in this scenario because it directly writes the file to the output buffer. In contrast, file_get_contents would read the entire file into memory, which is unnecessary and could be resource-intensive for large files.
The above is the detailed content of How to Efficiently Display Images Retrieved with file_get_contents in PHP?. For more information, please follow other related articles on the PHP Chinese website!