What are common pitfalls to avoid when working with file operations in PHP, such as echoing file handles directly?

One common pitfall to avoid when working with file operations in PHP is echoing file handles directly, as this can expose sensitive information or corrupt the output. Instead, it is recommended to read the contents of the file into a variable and then echo the variable to ensure proper handling of the file data.

// Avoid echoing file handles directly
$file = fopen("example.txt", "r");
echo $file;

// Correct way to handle file data
$file = fopen("example.txt", "r");
$fileContents = fread($file, filesize("example.txt"));
echo $fileContents;
fclose($file);