What best practices should be followed when saving user information in a text file using PHP?

When saving user information in a text file using PHP, it is important to follow best practices to ensure the security and integrity of the data. This includes properly sanitizing user input to prevent SQL injection attacks, encrypting sensitive information before storing it, and setting appropriate file permissions to restrict access to the file.

<?php
// Sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Encrypt sensitive information
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Save user information to a text file
$file = 'users.txt';
$data = "Username: $username, Email: $email, Password: $password\n";
file_put_contents($file, $data, FILE_APPEND);

// Set appropriate file permissions
chmod($file, 0600);
?>