← Back to Chapters

PHP getcwd(), chdir(), scandir()

? PHP getcwd(), chdir(), scandir()

? Quick Overview

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.

? Key Concepts

  • Working Directory – The directory where the script is currently operating.
  • Directory Navigation – Moving between folders during runtime.
  • Directory Scanning – Reading files and folders from a path.

? Syntax & Theory

  • getcwd() returns the absolute path of the current directory.
  • chdir(path) changes the current working directory.
  • scandir(path) returns an array of directory contents.

? Code Example

? View Code Example
// 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>";
}
?>

? Live Output / Explanation

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 ...

? Interactive Concept

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.

? Use Cases

  • File upload handling
  • Directory-based file management systems
  • Dynamic file listing scripts
  • Backup and log file navigation

✅ Tips & Best Practices

  • Always confirm directory changes using getcwd().
  • Filter out . and .. from scandir() results.
  • Ensure proper permissions before accessing directories.

? Try It Yourself

  • Check directory existence using is_dir() before calling chdir().
  • Create a function that scans directories recursively.
  • Experiment with absolute vs relative paths.