In the context of PHP file manipulation, what are the common pitfalls to avoid when removing specific lines based on user input from a form?

When removing specific lines based on user input from a form in PHP file manipulation, it is crucial to validate and sanitize the user input to prevent malicious code injection. Additionally, ensure that the file is opened in the correct mode for writing and handle errors appropriately to avoid data loss. Finally, make sure to properly iterate through the file contents, identify the lines to be removed, and rewrite the file without those lines.

<?php
// Validate and sanitize user input
$lineToRemove = filter_input(INPUT_POST, 'lineToRemove', FILTER_SANITIZE_NUMBER_INT);

// Open the file in read mode
$filename = 'example.txt';
$handle = fopen($filename, 'r');

// Open a temporary file for writing
$tmpFilename = 'temp.txt';
$tmpHandle = fopen($tmpFilename, 'w');

// Iterate through the file contents, removing the specified line
$lineNumber = 1;
while (($line = fgets($handle)) !== false) {
    if ($lineNumber != $lineToRemove) {
        fwrite($tmpHandle, $line);
    }
    $lineNumber++;
}

// Close the file handles
fclose($handle);
fclose($tmpHandle);

// Replace the original file with the temporary file
rename($tmpFilename, $filename);
?>