What potential pitfalls or errors could arise when using the chdir() function in PHP?

When using the chdir() function in PHP, potential pitfalls or errors could arise if the specified directory does not exist or if the script does not have the necessary permissions to access the directory. To avoid these issues, it is important to check if the directory exists and if the script has the required permissions before attempting to change directories.

$directory = '/path/to/directory';

if (is_dir($directory) && is_readable($directory)) {
    chdir($directory);
    echo "Changed directory to: " . getcwd();
} else {
    echo "Error: Directory does not exist or is not readable.";
}