Horje
How to search file directory with text recursive in PHP
To search for text within files in a directory and its subdirectories recursively using PHP, you can employ a function that utilizes RecursiveDirectoryIterator and RecursiveIteratorIterator. This approach provides a robust and efficient way to traverse the file system.

Change Directory Name

From full code at line 30 changes directory name.
Example: PHP
$searchDirectory = 'cache'; // Replace with the actual directory path

Change the keyword

Change the keyword/Text that you want to search from directory at line 30

$textToFind = 'html'; // Replace with the text you want to find

Full Code

Here is completed full code that you can use in your php file.

index.php
Example: PHP
<?php

function searchFilesRecursively(string $directory, string $searchText): array
{
    $results = [];
    try {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );

        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $filePath = $file->getPathname();
                $fileContents = file_get_contents($filePath);

                if ($fileContents !== false && strpos($fileContents, $searchText) !== false) {
                    $results[] = $filePath;
                }
            }
        }
    } catch (UnexpectedValueException $e) {
        // Handle cases where the directory might not exist or is not readable
        error_log("Error accessing directory: " . $e->getMessage());
    }
    return $results;
}

// Usage example:
$searchDirectory = 'cache'; // Replace with the actual directory path
$textToFind = 'html'; // Replace with the text you want to find

$foundFiles = searchFilesRecursively($searchDirectory, $textToFind);

if (!empty($foundFiles)) {
    echo "Text found in the following files:\n";
    foreach ($foundFiles as $file) {
        echo "- " . $file . "\n";
    }
} else {
    echo "Text not found in any files within the specified directory.\n";
}

?>

Output should be:





php function

Type:
Develop
Category:
Web Tutorial
Sub Category:
PHP Function Tutorial
Uploaded by:
Admin