What is the purpose of using fwrite in PHP and what potential pitfalls should be considered when using it?
The purpose of using fwrite in PHP is to write data to a file. When using fwrite, it is important to handle errors that may occur during the writing process, such as file permissions or disk space issues. Additionally, it is recommended to properly sanitize and validate the data being written to prevent security vulnerabilities.
$file = 'data.txt';
$data = 'Hello, World!';
$handle = fopen($file, 'w');
if ($handle === false) {
die('Cannot open file for writing');
}
if (fwrite($handle, $data) === false) {
die('Cannot write to file');
}
fclose($handle);