file_get_contents displaying image incorrectly

怎甘沉沦 提交于 2019-12-21 20:54:35

问题


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!


回答1:


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.




回答2:


try this one

$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,'">';



回答3:


echo 'data:;base64,'.base64_encode(file_get_contents('http://images.itracki.com/2011/06/favicon.png'));


来源:https://stackoverflow.com/questions/14250739/file-get-contents-displaying-image-incorrectly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!