What security considerations should be taken into account when using PHP to write data to files?

When writing data to files in PHP, it is important to consider security measures to prevent vulnerabilities such as directory traversal attacks or malicious code injection. One way to enhance security is to sanitize input data and validate file paths before writing to them. Additionally, restricting file permissions and using secure file handling functions can help mitigate potential risks.

// Sanitize input data and validate file path
$filename = '/path/to/directory/' . basename($_POST['filename']);

// Check if file path is within allowed directory
if (strpos(realpath($filename), '/path/to/directory/') !== 0) {
    die('Invalid file path');
}

// Write data to file with restricted permissions
file_put_contents($filename, $_POST['data'], LOCK_EX);