Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search on files in a folder

Tags:

php

I have a search box on my site. If a student enters some text, the script must search for files with that type of name in a folder.

How to read folder and search for files?

like image 782
RKh Avatar asked Dec 19 '25 08:12

RKh


1 Answers

Depending on your OS and the magnitude of files in the folder, you could go about it a few different ways. The simplest way would be to use glob():

$safer = escapeshellarg( $_REQUEST['search'] );
$results = glob( "$dir/*$safer*" );

This should give you the same results as "ls *something*" in that directory.

If you have a more specific search pattern in mind and a modest magnitude of files in the directory, scandir() will give you an array you could use preg_match() on.

If you have a vast number of files, you might consider leveraging /usr/bin/locate, or /usr/bin/find. These kinds of shell executions from php do incur system load. If you have a large number of students, or a public facing search, then you will want to pursue a different approach.

like image 138
memnoch_proxy Avatar answered Dec 21 '25 22:12

memnoch_proxy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!