What are some best practices for securely creating and writing to files in PHP?

When creating and writing to files in PHP, it is important to follow best practices to ensure the security of your application. One key practice is to validate user input and sanitize data before writing it to a file to prevent injection attacks. Additionally, it is recommended to set appropriate file permissions to restrict access to the file and avoid storing sensitive information in plain text.

// Example of securely creating and writing to a file in PHP

// Define the file path
$file = 'example.txt';

// Validate user input and sanitize data
$data = filter_var($_POST['data'], FILTER_SANITIZE_STRING);

// Open the file for writing
$handle = fopen($file, 'w');

// Check if the file was successfully opened
if ($handle) {
    // Write data to the file
    fwrite($handle, $data);
    
    // Close the file
    fclose($handle);
    
    echo 'Data has been written to the file.';
} else {
    echo 'Unable to open file for writing.';
}