What are common pitfalls when using fwrite in PHP?
Common pitfalls when using fwrite in PHP include not checking if the file was successfully opened, not handling errors properly, and not closing the file after writing to it. To solve these issues, always check if the file was opened successfully, handle errors using try-catch blocks, and close the file after writing to it using fclose().
<?php
$filename = "example.txt";
// Open the file for writing
$handle = fopen($filename, "w");
if ($handle === false) {
die("Cannot open file for writing");
}
// Write to the file
try {
fwrite($handle, "Hello, World!");
} catch (Exception $e) {
echo "Error writing to file: " . $e->getMessage();
}
// Close the file
fclose($handle);
?>