is_dir() function does not work as expected

Asked

Viewed 85 times

0

Greetings!
I am developing a file system to read the files of a given directory and return the value in JSON. However, I intend to separate in this JSON if the item is a file ("type":"file") or a folder("type":"folder").
For that, I’m using the function is_dir() (tried also with the function is_file()). Maass... Didn’t work, getting the following result:
inserir a descrição da imagem aqui
The code I used:

<?php
  header('Content-Type: application/json');

  $path = str_replace("\\", "/", './root');
  $dir  = dir($path);
  $json = array();

  while($file = $dir -> read()){
    if ($file != ".." && $file != "."){
      array_push(
        $json,
        array(
          'path'=>$path.'/'.$file,
          'file'=>$file,
          'type'=>(!is_dir($file)) ? 'file' : 'folder'
        )
      );
    }
  }

  echo json_encode($json);
?>
  • NOTE: I also tested using dirname(__FILE__) in place of ./ in the variable $path (so it’s inside the str_replace())

1 answer

0


I found the problem:
The function is_dir() returns false if the specified file does not exist and part of the folder in which the file .php is running, ie I was scanning the files from the folder ./ and not the folder ./root.
I found this problem testing with the function file_exists($file) and also getting a result false.
The solution would be to use the full path of the file as a function parameter. That is to say: use is_dir($path.'/'.$file) and not just is_dir($file), this way Php finds the file and becomes able to check it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.