What best practices should be followed when handling file and directory operations in PHP to ensure efficient and error-free code execution?

When handling file and directory operations in PHP, it is important to follow best practices to ensure efficient and error-free code execution. This includes properly checking for errors, closing file handles after use, using absolute paths when necessary, and sanitizing user input to prevent security vulnerabilities.

// Example of best practices when handling file operations in PHP

// Check if file exists before attempting to open it
$filename = 'example.txt';
if (file_exists($filename)) {
    $file = fopen($filename, 'r');
    
    // Process file contents
    
    fclose($file); // Close file handle after use
} else {
    echo 'File does not exist';
}

// Example of sanitizing user input before using it in file operations
$user_input = $_POST['user_input'];
$clean_input = filter_var($user_input, FILTER_SANITIZE_STRING);

// Use absolute paths to ensure correct file paths
$absolute_path = '/var/www/html/uploads/';
$upload_file = $absolute_path . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $upload_file);