What potential pitfalls should be considered when using PHP to write to a file on a server?
One potential pitfall when using PHP to write to a file on a server is the lack of proper file permissions, which can lead to security vulnerabilities. To mitigate this risk, it's important to ensure that the file permissions are set correctly to restrict access to only authorized users. Additionally, it's crucial to validate user input to prevent malicious code injection that could compromise the server.
$filename = 'example.txt';
$data = 'Hello, world!';
// Set the file permissions to restrict access
chmod($filename, 0644);
// Validate user input before writing to the file
$data = htmlspecialchars($data);
// Write data to the file
file_put_contents($filename, $data, FILE_APPEND);