What potential pitfalls should be avoided when using PHP to search and display text files?

One potential pitfall when using PHP to search and display text files is not properly sanitizing user input, which can lead to security vulnerabilities such as SQL injection or cross-site scripting attacks. To avoid this, always use prepared statements or input validation to sanitize user input before using it in file operations or displaying it on the webpage.

// Sanitize user input before using it in file operations
$search_term = filter_var($_GET['search'], FILTER_SANITIZE_STRING);

// Open the text file for reading
$filename = 'example.txt';
$file = fopen($filename, 'r');

// Search for the specified term in the text file
while (!feof($file)) {
    $line = fgets($file);
    if (stripos($line, $search_term) !== false) {
        echo $line . '<br>';
    }
}

// Close the file
fclose($file);