What are best practices for handling file permissions and directory access when using PHP functions like fopen?

When using PHP functions like fopen to access files and directories, it is important to ensure proper file permissions are set to prevent unauthorized access or modification. Best practices include setting appropriate permissions on files and directories, using absolute file paths, and validating user input to prevent directory traversal attacks.

// Set appropriate file permissions for writing to a file
$file = 'example.txt';
$handle = fopen($file, 'w');
if ($handle) {
    chmod($file, 0644); // Set file permissions to read and write for owner, read for group and others
    fclose($handle);
} else {
    echo 'Unable to open file for writing';
}

// Use absolute file paths to prevent directory traversal attacks
$directory = '/path/to/directory/';
$file = $directory . 'example.txt';
$handle = fopen($file, 'w');
if ($handle) {
    // File operations
    fclose($handle);
} else {
    echo 'Unable to open file for writing';
}