What are the best practices for setting up and troubleshooting PHP scripts that involve writing to files?

When setting up and troubleshooting PHP scripts that involve writing to files, it is important to ensure that the file permissions are set correctly to allow the PHP script to write to the file. Additionally, it is a good practice to check for errors and handle them gracefully to prevent any unexpected behavior.

<?php
$filename = "example.txt";
$data = "Hello, World!";

// Check if the file is writable
if (is_writable($filename)) {
    // Open the file for writing
    $file = fopen($filename, "w");

    // Write data to the file
    fwrite($file, $data);

    // Close the file
    fclose($file);

    echo "Data has been written to the file successfully.";
} else {
    echo "Cannot write to the file. Please check file permissions.";
}
?>