How to search file in folder by using php?
Asked Answered
P

4

5

I have a folder called allfiles, and there are some files in this folder, such as

 1212-how-to-sddk-thosd.html
 3454-go-to-dlkkl-sdf.html
 0987-sfda-asf-fdf-12331.html
 4789-how-to-fdaaf-65536.html

I use scandir to list all files, and now I need to find the file by with keywords, example to-dlkkl is the keyword, and I will get the file 3454-go-to-dlkkl-sdf.html.

Glob seems not work, and opendir and readdir are not work well, any ideas?

Positivism answered 25/1, 2018 at 13:51 Comment(1)
What did you try for glob? I'm thinking that you'll need something like this: glob("/path/to/allfiles/*to-dlkkl*")Gustavo
C
11

Use loop foreach and strpos function:

$files = scandir('allfiles');
foreach ($files as $file) {
    if (strpos('to-dlkkl', $file) !== false) {
         //file found
    }
}
Competitor answered 25/1, 2018 at 13:54 Comment(3)
Thank you so much.Positivism
You are wellcomeCompetitor
strpos is haystack needle, not needle haystackGroscr
C
3

I wonder why glob() function not working for it?

The below code should work I guess,

$existing_dir = getcwd();
// path to dir
chdir( '/var/www/allfiles/' );

foreach( glob( '*to-dlkkl*.html' ) as $html_file ) {
    echo $html_file . '<br />';
}

chdir( $existing_dir );
Cavanaugh answered 25/1, 2018 at 14:11 Comment(0)
S
2

you can use strstr to get actual file

$allfiles = scandir('./');
foreach ($allfiles as $file) {
    if (strstr($file, 'to-dlkkl')) {
        echo "file found"; //do what you want
    }
}
Salt answered 25/1, 2018 at 13:58 Comment(0)
E
0

If You want to search specific file under directory then you can use preg_match() .

<?php
  if ($handle = opendir('/var/www/html/j')) { // here add your directory
  $keyword = "index.php"; // your keyword
    while (false !== ($entry = readdir($handle))) {
        // (preg_match('/\.txt$/', $entry)) {
        if (preg_match('/'.$keyword.'/i', $entry)) {
            echo "$entry\n";
        }
    }

    closedir($handle);
}

?>
Elitism answered 25/1, 2018 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.