What are common pitfalls when using scandir() in PHP to read directories and how can they be avoided?

Common pitfalls when using scandir() in PHP include not checking for the "." and ".." directories returned, as they represent the current and parent directories. To avoid this, it's important to filter out these entries before processing the rest of the files.

// Get the list of files in a directory
$files = scandir($directory);

// Filter out "." and ".." entries
$files = array_diff($files, array('.', '..'));

// Process the remaining files
foreach ($files as $file) {
    // Do something with $file
}