What are the potential consequences of not properly handling file operations in PHP scripts?

Improper handling of file operations in PHP scripts can lead to security vulnerabilities such as directory traversal attacks, file disclosure, and unauthorized access. To prevent these issues, it is important to validate input, sanitize user-supplied data, and properly set file permissions.

// Example of properly handling file operations in PHP

$filename = 'example.txt';

// Check if the file exists before attempting to read or write
if (file_exists($filename)) {
    // Read the file contents
    $file_contents = file_get_contents($filename);
    
    // Write to the file
    file_put_contents($filename, 'New content');
    
    // Set appropriate file permissions
    chmod($filename, 0644);
} else {
    echo "File does not exist.";
}