Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show image using file_get_contents

how can I display an image retrieved using file_get_contents in php?

Do i need to modify the headers and just echo it or something?

Thanks!

like image 241
Belgin Fish Avatar asked Nov 26 '10 15:11

Belgin Fish


People also ask

What will the file_get_contents () return?

The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

What is the function file_get_contents () useful for?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string.

What is the difference between file_get_contents () function and file () function?

The file_get_contents() function reads a file into a string. The file_put_contents() function writes data to a file.

Is file_get_contents secure?

file_get_contents in itself appears safe, as it retrieves the URL and places it into a string. As long as you're not processing the string in any script engine or using is as any execution parameter you should be safe.


2 Answers

You can use readfile and output the image headers which you can get from getimagesize like this:

$remoteImage = "http://www.example.com/gifs/logo.gif"; $imginfo = getimagesize($remoteImage); header("Content-type: {$imginfo['mime']}"); readfile($remoteImage); 

The reason you should use readfile here is that it outputs the file directly to the output buffer where as file_get_contents will read the file into memory which is unnecessary in this content and potentially intensive for large files.

like image 119
robjmills Avatar answered Sep 30 '22 09:09

robjmills


$image = 'http://images.itracki.com/2011/06/favicon.png'; // Read image path, convert to base64 encoding $imageData = base64_encode(file_get_contents($image));  // Format the image SRC:  data:{mime};base64,{data}; $src = 'data: '.mime_content_type($image).';base64,'.$imageData;  // Echo out a sample image echo '<img src="' . $src . '">'; 
like image 44
Yaşar Xavan Avatar answered Sep 30 '22 09:09

Yaşar Xavan