PHP allows you to work with directories on the file system. For example, you can open a directory and read its contents, create or delete a directory, list all files in the directory, and so on.

1. Create New Directory

You can create a new and empty directory by calling the mkdir() function with the path and name of the directory to be created.

// The directory path
$dir = "testdir";

// Check the existence of directory
if(!file_exists($dir)){
// Attempt to create directory
if(mkdir($dir)){
echo "Directory created successfully.";
} else{
echo "ERROR: Directory could not be created.";
}
} else{
echo "ERROR: Directory already exists.";
}

2. Copy Files

You can copy a file from one location to another by calling copy() function with the file's source and destination paths as arguments. If the destination file already exists, it will be overwritten.

// Source file path
$file = "example.txt";

// Destination file path
$newfile = "backup/example.txt";

// Check the existence of file
if(file_exists($file)){
// Attempt to copy file
if(copy($file, $newfile)){
echo "File copied successfully.";
} else{
echo "ERROR: File could not be copied.";
}
} else{
echo "ERROR: File does not exist.";
}

3. Listing all files in a Directory

You can use the scandir() function to list files and directories inside the specified path. Following function recursively lists all files in a directory using PHP.

// Define a function to output files in a directory
function outputFiles($path){
// Check directory exists or not
if(file_exists($path) && is_dir($path)){
// Scan the files in this directory
$result = scandir($path);

// Filter out the current (.) and parent (..) directories
$files = array_diff($result, array('.', '..'));

if(count($files) > 0){
// Loop through retuned array
foreach($files as $file){
if(is_file("$path/$file")){
// Display filename
echo $file . "<br>";
} else if(is_dir("$path/$file")){
// Recursively call the function if directories found
outputFiles("$path/$file");
}
}
} else{
echo "ERROR: No files found in the directory.";
}
} else {
echo "ERROR: The directory does not exist.";
}
}

// Call the function
outputFiles("mydir");