What best practices should be followed when handling user input for file manipulation in PHP, especially when deleting specific lines?

When handling user input for file manipulation in PHP, especially when deleting specific lines, it is important to validate and sanitize the input to prevent malicious code injection. One way to do this is by using regular expressions to match and remove the specific lines from the file. Additionally, always make sure to back up the original file before making any changes to avoid data loss.

// Validate and sanitize user input
$lineToDelete = filter_input(INPUT_POST, 'line_number', FILTER_SANITIZE_NUMBER_INT);

// Read the file into an array
$lines = file('example.txt');

// Remove the specific line
if(isset($lines[$lineToDelete])) {
    unset($lines[$lineToDelete]);
}

// Save the updated content back to the file
file_put_contents('example.txt', implode('', $lines));