What are common reasons for the fopen() function to fail, and how can they be resolved in PHP?

Common reasons for the fopen() function to fail in PHP include incorrect file paths, insufficient permissions, and file locking issues. To resolve these issues, ensure that the file path is correct, check and adjust file permissions if needed, and make sure the file is not locked by another process.

$file = 'example.txt';

// Check if the file exists and is writable
if (file_exists($file) && is_writable($file)) {
    $handle = fopen($file, 'r');
    
    // Check if fopen was successful
    if ($handle) {
        // File operations can be performed here
        fclose($handle);
    } else {
        echo 'Error opening file';
    }
} else {
    echo 'File does not exist or is not writable';
}