user2688045
user2688045

Reputation:

How to search file in folder by using php?

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?

Upvotes: 5

Views: 27532

Answers (4)

Bhimrao Gadge
Bhimrao Gadge

Reputation: 106

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 );

Upvotes: 3

prakash tank
prakash tank

Reputation: 1267

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);
}

?>

Upvotes: 0

Soubhagya Kumar Barik
Soubhagya Kumar Barik

Reputation: 2595

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
    }
}

Upvotes: 2

Vladimir
Vladimir

Reputation: 1391

Use loop foreach and strpos function:

$files = scandir('allfiles');
foreach ($files as $file) {
    if (strpos('to-dlkkl', $file) !== false) {
         //file found
    }
}

Upvotes: 11

Related Questions