How to search file in folder by using php?
12,282
Solution 1
Use loop foreach
and strpos
function:
$files = scandir('allfiles');
foreach ($files as $file) {
if (strpos('to-dlkkl', $file) !== false) {
//file found
}
}
Solution 2
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 );
Solution 3
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
}
}
Author by
Admin
Updated on June 07, 2022Comments
-
Admin about 2 years
I have a folder called
allfiles
, and there are some files in this folder, such as1212-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, exampleto-dlkkl
is the keyword, and I will get the file3454-go-to-dlkkl-sdf.html
.Glob seems not work, and opendir and readdir are not work well, any ideas?