What are the best practices for handling file permissions in PHP when accessing files on the server?

When accessing files on the server in PHP, it is important to handle file permissions properly to ensure security and prevent unauthorized access. One best practice is to set the correct file permissions using chmod() function to restrict access to files based on their intended use.

// Set file permissions to restrict access
$file = 'example.txt';
$permissions = 0644; // Read and write for owner, read for others
if (file_exists($file)) {
    chmod($file, $permissions);
    echo "File permissions set successfully.";
} else {
    echo "File does not exist.";
}