How can one ensure proper error handling and security measures when working with file operations in PHP?

To ensure proper error handling and security measures when working with file operations in PHP, it is important to check for errors after each file operation, handle exceptions, and validate user input to prevent directory traversal attacks.

// Example of proper error handling and security measures when working with file operations in PHP

// Check if file exists before performing any operations
$file = 'example.txt';
if (file_exists($file)) {
    // Perform file operations
    $content = file_get_contents($file);
    echo $content;
} else {
    echo 'File does not exist.';
}

// Use try-catch block to handle exceptions
try {
    $file = fopen('example.txt', 'r');
    if (!$file) {
        throw new Exception('Unable to open file.');
    }
    // Perform file operations
    fclose($file);
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

// Validate user input to prevent directory traversal attacks
$filename = 'example.txt';
if (strpos($filename, '..') === false) {
    // Perform file operations
    $content = file_get_contents($filename);
    echo $content;
} else {
    echo 'Invalid filename.';
}