What potential pitfalls should be considered when using PHP to write data to a .php file?
One potential pitfall when using PHP to write data to a .php file is the risk of code injection if the data being written is not properly sanitized. To mitigate this risk, always validate and sanitize user input before writing it to a file. Additionally, ensure that the file permissions are set correctly to prevent unauthorized access.
// Sanitize user input before writing to file
$data = filter_var($_POST['data'], FILTER_SANITIZE_STRING);
// Write sanitized data to file
$file = 'data.php';
$handle = fopen($file, 'w');
fwrite($handle, '<?php $data = "' . $data . '"; ?>');
fclose($handle);
// Set file permissions
chmod($file, 0644);