What are some best practices for incorporating fwrite() return values into success messages in PHP?

When using the fwrite() function in PHP to write data to a file, it is important to check the return value to ensure that the data was written successfully. Incorporating fwrite() return values into success messages can provide valuable feedback to the user about the outcome of the operation. One best practice is to use an if statement to check if fwrite() returns false, indicating an error, and display an appropriate error message. If fwrite() returns the number of bytes written, you can display a success message to confirm that the data was written successfully.

$file = 'example.txt';
$data = 'Hello, World!';

$handle = fopen($file, 'w');
if ($handle === false) {
    echo 'Error opening file';
} else {
    $bytes_written = fwrite($handle, $data);
    if ($bytes_written === false) {
        echo 'Error writing to file';
    } else {
        echo 'Data written successfully: ' . $bytes_written . ' bytes';
    }
    fclose($handle);
}