Search code examples
phpfile-get-contents

file_get_contents displaying image incorrectly


I'm trying to display generic websites and URLs as part of my own site. Here's part of the relatively simple code I'm using:

browse.php

<?   
$enteredurl = $_GET["url"];
$page = file_get_contents($enteredurl);
echo $page;
?>

Ignoring the fact that some links/images will not work if the URls are relative rather than absolute, this works just fine. Pages are accessed using $_GET, something like

browse.php?url=http://itracki.com

The webpage will display as expected. However, when I'm trying to get something else, like an image, I get something like this, which I'm thinking is binary or something?

browse.php?url=http://images.itracki.com/2011/06/favicon.png

‰PNG  IHDRóÿa%IDAT8Ëc8sæÌJ0M ```ã3`xaÔ€aa]r#f.–ÄíNIEND®B`‚

I've been looking online and tried modifying the page headers, something like

<? header('Content-type: image/png;'); ?>

but I'm still getting the same jumbled up result. Does anyone know how I can actually see the image as it is if I were just accessing it by typing "http://images.itracki.com/2011/06/favicon.png" into the address bar?

Thanks!


Solution

  • Try this:

    <?php
      $img = 'http://images.itracki.com/2011/06/favicon.png';
      $info = getimagesize($img);
      header('Content-type: ' . $info['mime']);
      readfile($img);
    ?>
    

    You should use readfile() instead of file_get_contents() in this situation because readfile() will send the file contents directly to the browser rather than storing it in memory for a later retrieval, which is what file_get_contents() does.

    Also note that the content-type is retrieved dynamically so that you don't have to worry about specifying it incorrectly in the header.

    Some images may have an extension that doesn't match its content-type or mime-type, so this corrects for those type of issues.