Are there any best practices to follow when saving text from a textarea into files in PHP?

When saving text from a textarea into files in PHP, it is important to sanitize the input to prevent any malicious code injection. Additionally, it is recommended to specify a secure file path for saving the file and handle any potential errors that may occur during the file writing process.

<?php
// Get the text from the textarea
$text = $_POST['textarea'];

// Sanitize the input
$sanitized_text = htmlspecialchars($text);

// Specify the file path
$file_path = 'files/output.txt';

// Write the text to the file
if(file_put_contents($file_path, $sanitized_text) !== false){
    echo 'Text saved successfully.';
} else {
    echo 'Error saving text to file.';
}
?>