⊗ppPmFSDPC 350 of 447 menu

Analyzing Folder Contents in PHP

Suppose we have a folder dir, containing both files and folders.

Let's get an array of names from this folder:

<?php $files = array_diff(scandir('dir'), ['..', '.']); ?>

Let's check for each name whether it is a file or a folder:

<?php $files = array_diff(scandir('dir'), ['..', '.']); foreach ($files as $file) { echo $file; var_dump(is_file('dir/' . $file)); } ?>

Please note that the name of the folder we are scanning is written in two places in the code. This is not very convenient. Let's move this name to a separate variable:

<?php $dir = 'dir'; $files = array_diff(scandir($dir), ['..', '.']); foreach ($files as $file) { echo $file; var_dump(is_file($dir. '/' . $file)); } ?>

Now let's output the contents of all files to the screen:

<?php $dir = 'dir'; $files = array_diff(scandir($dir), ['..', '.']); foreach ($files as $file) { if (is_file($dir. '/' . $file)) { echo file_get_contents($dir. '/' . $file); } } ?>

It can be noticed that the path to the file is calculated twice. Let's move it to a separate variable:

<?php $dir = 'dir'; $files = array_diff(scandir($dir), ['..', '.']); foreach ($files as $file) { $path = $dir. '/' . $file; // file path if (is_file($path)) { echo file_get_contents($path); } } ?>

A folder is given. Display a column of names of subfolders from this folder.

A folder is given. Display a column of names of files from this folder.

A folder is given. Append the current timestamp to the end of each file in this folder.

byenru