文件获取内容是显示图像代码而不是实际图像

时间:2015-01-05 18:18:17

标签: php

我正在使用file_get_contents来访问一个文件夹,其中包含使用以下代码拒绝所有htaccess的图片:

      $idimages = 0; 
      while ($idimages < $edituser->idimages){ 
      //$edituser->verifyimg is stored like 123.png,image.png,another.jpg
      $imghref = explode(",",$edituser->verifyimg); 
      if (file_exists('userverify/'.$imghref[$idimages])) { 
      $imginfo = getimagesize('userverify/'.$imghref[$idimages]);
      header("Content-type: ".$imginfo['mime']); 
      echo file_get_contents('userverify/'.$imghref[$idimages]);
      //I was using this echo until I introduced the deny all htaccess and it no longer works
      //echo '<img src="'.URL." userverify/ ".$imghref[$idimages].'">&nbsp;'; 
      }
      $idimages++; 
      }

但是当我查看我的页面时,它会显示许多奇怪的字符。我对自己的错误感到困惑。 userverify是文件夹。

5 个答案:

答案 0 :(得分:2)

放标题(&#39; Content-Type:image / jpeg&#39;);在while循环之外。

你只能以这种方式显示1张图片。

如果要显示多个图像,可以使用base64内联或将所有图像合并为一个。

合并有点复杂。所以我建议你使用base64内联。

if(file_exists(&#39; userverify /&#39;。$ imghref [$ idimages])){

    $content = base64_encode(file_get_contents('userverify/'.$imghref[$idimages]));
    ?>
    <img src = "data:image/jpg;base64,<?=$content?>" />
    <?php
}

答案 1 :(得分:0)

这就是为什么您的网络服务器认为您想要提供文本,所以这个奇怪的字符是图像的源代码。

您需要的是设置正确的内容类型,这可以通过标题功能获得。

如果这不起作用,请检查cURL或您的浏览器是否真的发送了标题。

答案 2 :(得分:0)

认为你做错了就是你将图像显示为纯文本(至少你的服务器是这么认为的),而字符只是纯文本的图像。 把 header('Content-Type: image/jpeg'); ouside while while循环应解决它

那是什么?它只是将您的服务器设置为将图像显示为图像。不是文字。

答案 3 :(得分:0)

你不能这样做。通常,image-src是服务器加载文件的请求。带有file_get_contents的PHP只是抓取/读取yout图像文件的内容(二进制)!!以这种方式回传该源中的二进制文件是不可能的。将错过标题,并且无法猜出它必须显示的内容。

你可以做的事情:

(1)按照Marc的评论。 =&GT;将代码包装到yourscript.php并告诉src请求此文件。重要的是,你需要发送适当的标题(MIME)

(2)在image-src中使用base64

<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents(...)); ?>" />

答案 4 :(得分:0)

  1. 您不能一次呈现多个图像。
  2. 你应该使用readfile()而不是echo file_get_contents(),文件数据直接输出,不读入内存然后输出。
  3. 您不应将图片数据嵌入页面源。
    1. 它会增加页面源,延长页面加载时间。
    2. 不会并行下载图像,延长页面加载时间。
    3. 图像不会被缓存,浪费网络/ IO带宽并延长可能使用缓存图像的后续页面加载。
  4. show_protected_image.php

    <?php
    $folder = '/path/to/denyall'
    
    if( ! check_authorization() ) {
      header('HTTP/1.0 403 Forbidden');
      die('Access forbidden.');
    }
    
    $filepath = $folder.'/'.shell_escape($_GET['filename']);
    
    if( ! file_exists($filepath) ) {
      header('HTTP/1.0 404 Not Found');
      die('File not found');
    }
    
    session_write_close();
    /* only one session can be open at a given time, closing it here
       allows the other images to begin downloading without waiting
       for this one to finish. */
    header("Content-type: ".$mimetype);
    readfile($filepath);
    

    show_images.php

    <?php
    foreach($imagelist as $image) {
      printf('<img src="show_protected_image.php?filename=%s">', $image);
    }