【问题标题】:Read file in php and set it to the img src in html在php中读取文件并将其设置为html中的img src
【发布时间】:2015-07-08 08:21:13
【问题描述】:

如何在 php 中从服务器上的 images 文件夹(权限 644)中读取文件并将其动态设置为 html 的 img src? 我已经尝试了以下

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    $name = './images/approved.jpg';
    //$fp = readfile($name);
    $im = imagecreatefromjpeg($name);

    echo "<img src='data:image/jpg;base64,+ 'base64_encode($im), alt='Approved Videos''>";

    exit;
?>

我也尝试了以下

<div id="videoThumbnails">
                        <p>Thumbnail</p>
                        <a href="#" class="thumbnail">
                                   <!-- <img src="/phpVA/thumbnails/a.mp4.jpg" alt="Denied Videos">-->
                                   <?php 
                                        $name="/phpVA/thumbnails/a.mp4.jpg";
                                        $im = file_get_contents($name);
                                        echo "<img src='data:image/jpg;base64,".base64_encode($im)."' alt='Approved Videos'>";
                                    ?>
                        </a>

                      </div>

输出是

<img src="data:image/jpg;base64," alt="Approved Videos">

【问题讨论】:

  • 到目前为止你尝试了什么?
  • @kamalpal 我已经编辑了我的问题,以包括我迄今为止尝试过的内容

标签: php html


【解决方案1】:

试试file_get_contents

$im = file_get_contents($name);
echo "<img src='data:image/jpg;base64,".base64_encode($im)."' alt='Approved Videos'>";

【讨论】:

  • 嗨@Damien 它给了我 file_get_contents() : failed to open stream permission denied 。先生,我应该在这个文件夹上设置什么权限?
  • 您的权限似乎正确:644 应该足够了。检查您的网络服务器配置 (apache) 或 php.ini 是否有任何可能拒绝文件访问的内容?
【解决方案2】:

我建议使用file_get_contents 来获取文件内容,并使用base64 对这些内容进行编码。这是我在一个项目中使用的一个很好的例子:

$path = './images/approved.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

【讨论】:

  • 我在获取 file_get_contents 时遇到权限问题。文件夹的权限应该是什么。我已为 apache 所有者 www-data 将它们设置为 755。
  • 将目录的所有者更改为运行 PHP 的用户,很可能是 Web 服务器进程
猜你喜欢
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多