PHP provides built-in directory handling functions such as getcwd(), chdir(), and scandir(). These functions help you identify the current working directory, change directories during script execution, and list files or folders inside a directory.
getcwd() returns the absolute path of the current directory.chdir(path) changes the current working directory.scandir(path) returns an array of directory contents.
// Demonstrating getcwd(), chdir(), and scandir()
<?php
$current_directory = getcwd();
echo "Current Directory: $current_directory<br>";
$directory_to_change = "./myFolder";
if (chdir($directory_to_change)) {
echo "Directory changed to: " . getcwd() . "<br>";
} else {
echo "Failed to change directory.<br>";
}
$files = scandir($directory_to_change);
echo "Files in directory:<br>";
foreach ($files as $file) {
echo $file . "<br>";
}
?>
The script first prints the current working directory. After changing the directory using chdir(), it confirms the new directory and lists all files using scandir(). The output also includes special entries like . and ...
Think of the working directory like your current folder in a file explorer. Using chdir() is similar to double-clicking another folder, while scandir() is like viewing all files inside it.
getcwd().. and .. from scandir() results.is_dir() before calling chdir().