What are some common pitfalls to avoid when working with PHP scripts that involve reading and processing multiple files in different directories?

One common pitfall when working with PHP scripts that involve reading and processing multiple files in different directories is not properly handling file paths. To avoid this issue, always use absolute file paths when reading files to ensure the script can locate them correctly regardless of the current working directory.

// Get absolute path to the directory containing the files
$directory = '/path/to/directory';

// Open directory
$handle = opendir($directory);

// Loop through files in directory
while (false !== ($file = readdir($handle))) {
    // Check if file is a regular file
    if (is_file($directory . '/' . $file)) {
        // Process the file
        $content = file_get_contents($directory . '/' . $file);
        // Do something with the file content
    }
}

// Close directory handle
closedir($handle);