What are common pitfalls when using PHP to save user input to a text file, and how can they be avoided?

Common pitfalls when saving user input to a text file using PHP include not properly sanitizing the input, not validating the input, and not handling file permissions correctly. To avoid these pitfalls, always sanitize and validate user input before saving it to a file, and ensure that the file has the correct permissions set to prevent unauthorized access.

// Sanitize and validate user input
$user_input = $_POST['user_input'];
$user_input = filter_var($user_input, FILTER_SANITIZE_STRING);
if (empty($user_input)) {
    echo "Invalid input";
    exit;
}

// Save user input to a text file
$file = 'user_input.txt';
$fh = fopen($file, 'a');
if ($fh) {
    fwrite($fh, $user_input . PHP_EOL);
    fclose($fh);
    echo "User input saved successfully";
} else {
    echo "Error saving user input";
}