Skip to content
PHP Logo

What are the potential pitfalls of implementing a search function in PHP that searches through files?

One potential pitfall of implementing a search function in PHP that searches through files is the risk of exposing sensitive information or compromising security if not properly sanitized. To mitigate this risk, it is important to validate user input and sanitize search queries before executing them.

php
// Sanitize search query before using it to search through files
$search_query = filter_var($_GET['search'], FILTER_SANITIZE_STRING);

// Check if search query is not empty before proceeding
if (!empty($search_query)) {
    // Implement search functionality here
    // Example: search through files in a directory
    $files = glob('path/to/files/*.txt');
    
    foreach ($files as $file) {
        $content = file_get_contents($file);
        
        if (stripos($content, $search_query) !== false) {
            echo "Found in file: $file";
        }
    }
} else {
    echo "Please enter a search query.";
}