What improvement can be made in the PHP script to optimize the search process in the user file?

The issue with the current PHP script is that it iterates through the entire user file for each search query, which can be inefficient for large files. To optimize the search process, we can implement a caching mechanism using PHP sessions. By storing the user file data in a session variable, we can avoid reading the file multiple times and improve the search performance.

<?php
session_start();

// Check if user file data is already stored in session
if (!isset($_SESSION['user_file_data'])) {
    // Read user file data and store it in session
    $user_file_data = file_get_contents('users.txt');
    $_SESSION['user_file_data'] = $user_file_data;
} else {
    $user_file_data = $_SESSION['user_file_data'];
}

// Perform search in the user file data
$search_query = $_GET['search_query'];
$found_users = [];

$lines = explode("\n", $user_file_data);
foreach ($lines as $line) {
    if (stripos($line, $search_query) !== false) {
        $found_users[] = $line;
    }
}

// Output the found users
foreach ($found_users as $user) {
    echo $user . "<br>";
}
?>