What best practices should be followed when dealing with file paths in PHP to avoid errors like "failed to open stream"?

When dealing with file paths in PHP, it is essential to use the correct directory separators and ensure that the paths are properly formatted. This includes using the DIRECTORY_SEPARATOR constant to handle file paths in a platform-independent manner. Additionally, it is crucial to check for file existence before attempting to open or manipulate it to avoid errors like "failed to open stream".

// Example of using DIRECTORY_SEPARATOR and checking file existence
$file_path = 'path/to/file.txt';
if (file_exists($file_path)) {
    $file_handle = fopen($file_path, 'r');
    // Perform operations on the file
    fclose($file_handle);
} else {
    echo 'File does not exist.';
}