What are some common pitfalls to avoid when using PHP to create and write to files?

One common pitfall to avoid when using PHP to create and write to files is not checking if the file exists before attempting to write to it. This can lead to overwriting existing files or encountering errors. To solve this issue, you should first check if the file exists and handle it accordingly.

$filename = 'example.txt';

if (file_exists($filename)) {
    echo "File already exists. Cannot overwrite.";
} else {
    $file = fopen($filename, 'w');
    fwrite($file, 'Hello, World!');
    fclose($file);
    echo "File created and written successfully.";
}