1

Im only a begginer in PHP so Im really sorry if it is just a stupid question.I have a directory full of .txt files and I have written a code to find a specific string inside those files and echo the whole line :

<?php
$search = $_POST['search'];
$dir = 'C:\xampp\htdocs\myfiles\dbl';
$files = scandir($dir,1);
foreach ($files as $lines){
    foreach($lines as $line)
    {
    if(strpos($line, $search) !== false)
    echo $line;
    }
}
?>

However,I keep getting this error : Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\myfiles\search.php on line 19

1
  • If you need speed on many large files then have a look at running grep from PHP using shell_exec. Commented Jul 25, 2016 at 13:56

3 Answers 3

2

This error caused by fact that you actually didn't open file within 1-st loop. You must open each file before looping throw lines. You can do it with two ways:

1) Using file_get_contents() function

2) Using some functions for work with files (fopen(), fclose(), etc)

Go here

Sign up to request clarification or add additional context in comments.

Comments

2
$search = 'test';
$dir = 'C:\xampp5.6\htdocs';
$files = scandir($dir,1);
foreach ($files as $lines){
    if(strlen($lines) > 3 && strpos($lines, '.txt') !== false){
        $readfile = fopen('C:\xampp5.6\htdocs/'.$lines, 'r');

        while(!feof($readfile)) {
            $contents = fgets($readfile);
            if(strpos($contents, $search) !== false)
                echo $lines.'<br>';
        }
        fclose($readfile);
    }
}

2 Comments

This worked perfectly,thanks! But how can I make it case insensitive? strtolower is very slow because my files are large.
you can user stripos($contents, $search) too.
0

Use fopen() to read each file and then search for the string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.