如何修复PHP中的“警告:scandir:无法打开目录”错误

时间:2019-03-30 09:17:28

标签: php

我扫描文件夹以显示其中的所有图片。如何设置文件夹的绝对路径?

图片位于// localhost / img / gallery /文件夹中。

有两个index.php文件。第一个-在根目录中。第二个在文件夹“ en”中。 首先,该功能运行良好。在第二个函数中,将文件夹“ en”添加到URL。而不是“ localhost / img / gallery /”-原来是“ localhost / en / img / gallery /”。 如果将站点地址添加到目录,则路径正确。但是出现错误:“警告:scandir(// localhost / img / gallery /):无法打开dir:未实现”。

// in function.php:

function GetImages($path){
   $wimg = "";
   $fimg = "";
   $images = scandir($path);
   if ($images !== false) {
      $images = preg_grep("/\.(?:png|gif|jpe?g)$/i", $images);
      if (is_array($images)) {
         foreach($images as $image) {
            $fimg .= '
                  <a href="'.$path.htmlspecialchars(urlencode($image)).'">
                     <img src="'.$path.htmlspecialchars(urlencode($image)).'">
                  </a>
            ';
         }
         $wimg .= $fimg;
      } else {
         $wimg .= "<p>No images in directory!</p>";
      }
   } else {
      $wimg .= "<p>Error.</p>";
   }
   echo $wimg;
}

// in index.php:

<?php GetImages("img/gallery/");?> // it's Ok

// in en/index.php:

<?php GetImages("img/gallery/");?> // it turns out "localhost/en/img/gallery/". But there are no pictures.

// if in en/index.php:
<?php GetImages("localhost/img/gallery/");?> // it turns out "Warning: scandir(//localhost/img/gallery/): failed to open dir: not implemented in D:\OpenServer\domains\localhost\function.php on line XXX"

所以也是一个错误:

// in function.php
function GetImages(){
   $wimg = "";
   $fimg = "";
   $path = $_SERVER['SERVER_NAME'] . "/img/gallery/";
// in index.php and in en/index.php
<?php GetImages();?> // "Warning: scandir(localhost/img/gallery/,localhost/img/gallery/): ������� �� ������ ����� �������� ���. (code: 3) in D:\OpenServer\domains\localhost\function.php on line XXX"

但是

// in function.php
function GetImages(){
   $wimg = "";
   $fimg = "";
   $path = "/img/gallery/";
// in index.php
<?php GetImages();?> // it's Ok
// in en/index.php
<?php GetImages();?> // it turns out "localhost/en/img/gallery/". But there are no pictures.

dirname( FILE )。也是错误的。

1 个答案:

答案 0 :(得分:1)

尝试一下,

scandir(__DIR__ .$path);