What potential pitfalls should be considered when trying to write to a file in PHP?

One potential pitfall when trying to write to a file in PHP is not properly handling file permissions. Make sure that the directory where you are trying to write the file has the correct permissions set to allow PHP to write to it. Additionally, be cautious of file path injection vulnerabilities that could allow malicious users to write to unintended locations on the server.

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

// Check if the directory has the correct permissions
if (is_writable(dirname($file))) {
    // Open the file for writing
    $handle = fopen($file, 'w');
    
    // Write data to the file
    fwrite($handle, $data);
    
    // Close the file
    fclose($handle);
    
    echo "Data written to file successfully.";
} else {
    echo "Cannot write to file due to insufficient permissions.";
}