What are some best practices for handling file permissions and ownership when using fopen in PHP to avoid errors like "failed to open stream: No such file or directory"?

When using fopen in PHP, it is essential to ensure that the file path is correct and that the file exists. To avoid errors like "failed to open stream: No such file or directory", you should check the file permissions and ownership to ensure that the PHP script has the necessary access rights to read or write to the file.

$file_path = '/path/to/file.txt';

if (file_exists($file_path)) {
    if (is_readable($file_path)) {
        $file = fopen($file_path, 'r');
        // perform operations on the file
        fclose($file);
    } else {
        echo "File is not readable.";
    }
} else {
    echo "File does not exist.";
}