is_file()和is_dir()不起作用

时间:2017-05-27 08:51:16

标签: php

我正在为文件哈希编写一个类但是我在开始时遇到了困难。

class fileHashing
{
    private $start_path = '../../../test';
    private $log_path   = '../../../test/log';
    private $log_file   = 'fileHash.xyz';

    function __construct()
    {
        $this->open();
    }

    private function open() {
        $files_list = scandir($this->start_path);
        print_r($files_list);
        date_default_timezone_set('Europe/Rome');
        foreach ($files_list as $key => $element) {
            if (is_file($element)) {
                echo "FILE: " . $element . PHP_EOL;

            } elseif (is_dir($element)) {
                echo "DIR: " . $element . PHP_EOL;
            } else {
                echo "NONE: " . $element . PHP_EOL;
            }
        }
    }
}

$a = new fileHashing();

返回:

Array
(
    [0] => .
    [1] => ..
    [2] => fileupload.php
    [3] => log
    [4] => test1.php
    [5] => tsconfig.json
)
DIR: .
DIR: ..
FILE: fileupload.php
NONE: log
NONE: test1.php
NONE: tsconfig.json

log是一个文件夹,但无法识别它,test1.phptsconfig.json都无法识别为文件。 我错过了关于scandir() / is_file() / is_dir()的内容吗?

2 个答案:

答案 0 :(得分:1)

使用这种方式: -

if (filetype($this->start_path . '/' . $element) == "dir") {
  // dir
}elseif(filetype($this->start_path . '/' . $element) == "file") {
  // file
}
// or this way
if (is_dir($this->start_path . '/' . $element)) {
  // dir
}elseif(is_file($this->start_path . '/' . $element)) {
  // file
}

答案 1 :(得分:0)

您还应该将start_path附加到is_fileis_dir内的文件名中。可以这样做

private function open() {
    $files_list = scandir($this->start_path);
    print_r($files_list);
    date_default_timezone_set('Europe/Rome');
    foreach ($files_list as $key => $element) {
        $file = $this->start_path . '/' . $element;
        if (is_file($file)) {
            echo "FILE: " . $element . PHP_EOL;

        } elseif (is_dir($file)) {
            echo "DIR: " . $element . PHP_EOL;
        } else {
            echo "NONE: " . $element . PHP_EOL;
        }
    }
}