What are the best practices for handling directory permissions and access restrictions when working with PHP scripts that interact with external files on web servers?

When working with PHP scripts that interact with external files on web servers, it is important to properly handle directory permissions and access restrictions to ensure the security of the files. One best practice is to restrict access to sensitive directories by setting appropriate permissions. This can help prevent unauthorized users from viewing or modifying critical files on the server.

// Set directory permissions to restrict access
$directory = '/path/to/directory/';

// Check if directory exists
if (is_dir($directory)) {
    // Set permissions to allow only owner to read, write, and execute
    chmod($directory, 0700);
} else {
    // Handle error if directory does not exist
    echo "Directory does not exist.";
}