What are common pitfalls to be aware of when using fwrite() in PHP?

One common pitfall when using fwrite() in PHP is not checking if the file was successfully opened before attempting to write to it. This can lead to errors if the file cannot be opened for writing. To solve this, always check the return value of fopen() before proceeding with fwrite(). Additionally, it's important to handle any potential errors that may occur during the writing process to ensure the data is written correctly.

$file = 'example.txt';
$handle = fopen($file, 'w');
if ($handle !== false) {
    if (fwrite($handle, 'Hello, World!') === false) {
        echo 'Error writing to file';
    } else {
        echo 'Data written successfully';
    }
    fclose($handle);
} else {
    echo 'Error opening file';
}