获取文件名+文件夹中的图像路径 - PHP

时间:2014-01-22 14:41:09

标签: php image path filenames

我的脚本指向存储图像的文件夹。

我想检索图像的文件名和路径名,以便在调用时加载我的图像(参见下面的html / php代码)。

我尝试过以下操作,但收到错误消息:

Failed to open stream: Permission denied

在这行代码$page = file_get_contents($fileinfo->getPathname());

PHP

public function action_mybook($page = '') {

    FB::log($this->request->param('id1'));
    $this->template->content = View :: factory('mybook/default');
    // give me a list of all files in folder images/mybook_images
    $dir = new DirectoryIterator('images/mybook/');
    $this->template->content->pages = array('.$dir.');
    foreach ($dir as $fileinfo) {
        if (!$fileinfo->isDot()) {
            $pages[] = $fileinfo->getFilename();
            $page = file_get_contents($fileinfo->getPathname());
        }
    }
  }

HTML / PHP

<div id="book">
        <!-- Next button -->
        <div ignore="1" class="next-button"></div>
        <!-- Previous button -->
        <div ignore="1" class="previous-button"></div>
        <?php
        foreach ($pages as $page) {
            echo '<div><img src="'.$page.'" /></div>';
        }
        ?>
    </div>

如果我注释掉$page = file_get_contents($fileinfo->getPathname());行并且没有错误并且创建了图片的div,但它显示“未能加载给定的网址”

使用echo '<img src="myimage.png">' it displays the image

手动加载图像

4 个答案:

答案 0 :(得分:1)

可能的问题

目录分隔符

我尝试执行代码并获得相同的代码。 Whhy?因为/。在Windows中\。返回网址无效:

images/mybook\arrows.png

正确的是:

images\mybook\arrows.png

or images/mybook/arrows.png (linux... in windows works too)

因此,您需要使用PHP的DIRECTORY_SEPARATOR常量,这可以解决您的问题。见下文:

<强>更新

我只需将$page添加到DirectoryIterator中的网址末尾。

public function action_mybook($page = '') {

  FB::log($this->request->param('id1'));
  $this->template->content = View :: factory('mybook/default');

  $dir = new DirectoryIterator('images' . DIRECTORY_SEPARATOR . 'mybook' . DIRECTORY_SEPARATOR . $page);
  $this->template->content->pages = array('.$dir.');

  foreach ($dir as $fileinfo) {

    if (!$fileinfo->isDot()) {
      $pages[] = $fileinfo->getPathname();
    }

  }

}

我希望这有帮助。

抱歉我的英语。

答案 1 :(得分:0)

更改777目录中文件的权限,然后重试

答案 2 :(得分:0)

尝试评论此行:

$page = file_get_contents($fileinfo->getPathname());

我不知道,您需要将图像文件读取到变量。

检查完整的图片路径,试试这个:

$pages[] = 'images/mybook/'.$fileinfo->getFilename();

$pages[] = '/images/mybook/'.$fileinfo->getFilename();

与您的项目路径有关。

答案 3 :(得分:-1)

尝试授予您的图片权限,您可以使用chmod提供权限:

chmod($fileinfo->getPathname(),0777);//add this line in your code
$page = file_get_contents($fileinfo->getPathname());

注意:$ fileinfo-&gt; getPathname()应该返回图像路径。

相关问题