What security measures can be implemented to prevent unauthorized access to files in a PHP script?

To prevent unauthorized access to files in a PHP script, you can implement security measures such as using file permissions to restrict access, storing sensitive files outside of the web root directory, and using authentication mechanisms to control access.

// Example of restricting access to a file using file permissions
$filename = 'sensitive_file.txt';

// Set file permissions to restrict access
if (!file_exists($filename)) {
    touch($filename);
    chmod($filename, 0600); // Only the owner can read and write
}

// Code to read or write to the file