Skip to content
Programming Updated Dec 2017

Tree Function in PHP, Show all files and directories in a directory in PHP

PHP has no built-in tree command. This recursive PHP function lists every file and subfolder in a directory, just like the Windows tree command.

Published
Reading time
1 min read
Views
3.2k views
Tree Function in PHP, Show all files and directories in a directory in PHP

We use Tree function in Widnows Command Prompt to show all the directories and files in certain directory. But in PHP there is not default function to show or to get all files and directories so i have write a function that is similar to CMD TREE function. And by using this function you can get all files and directories from a path.

tree(); function.

How to use this function:

$tree = tree("your desired path");

function tree($path, $exclude = array()) {
$files = array();
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $splfileinfo) {
if (!in_array(basename($splfileinfo), $exclude)) {
$files[] = str_replace($path, '', '' . $splfileinfo);
}
}
return $files;
}

Questions & comments

Did this work for you, or did you hit a different error? Ask below and we will help.

Comments are reviewed before they appear.

More like this

More in Programming

Programming

Draw sine function with PHP code on an image.

Now we learn how to draw a sine function in PHP. It is very simple and easy to draw sine function in PHP language. This function will generate a sine wave on image. Watch…

Programming

PHP code to draw tan function on an image

In this article you will learn about tan function. How to draw tan function on an image with PHP code. Mostly these functions are used in mathematics, computer pixels and…

Programming

PHP code to draw ellipse with Standard equation on an image

In this tutorial you will learn how to draw an Ellipse on an image with PHP code. This is mostly used in Numerical Computing and Mathematics to draw graphs from algebraic…

Programming

PHP code to draw a parabola and create image

Hello Friends today i will discuss how to draw a parabola with PHP code and create an image. We will draw this parabola with standard equation. <?php $x = 400; $y = 400;…