问题
I have a search feature on my website. I would like it to search through a certain folder for files on my server and display results from there. I'd rather not use databases.
Is there a way to do this?
回答1:
<?php
$dir = "/your_folder_here/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == $_POST['SEARCHBOX_INPUT']){
echo('<a href="'.$dir . $file.'">'. $file .'</a>'."\n");
}
}
closedir($dh);
}
}
?>
From php.net mostly. Obviously change your file path. Also change the $_POST command in the middle to whatever the name of your search box input is. This will only find exact matches of your search. Some changes could be made to find close matches.
回答2:
$dir = "/etc/php5/";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == 'songs1.php')
//ur code here ...
}
closedir($dh);
}
}
I got this from PHP.net. I hope this helps you.
回答3:
This is how I did it, although it displays all the files which are in that directory and it does not give a brief description of each file. I dont know if you can help modify it.
<?php
print "<h2>Showing results for $search</h2>";
$dirName="MYBOOKS";
$dp=opendir($dirName);
chdir($dirName);
while ($currentFile !== false) {
$currentFile = readDir($dp);
$theFiles[] = $currentFile;
}
$BookFiles= preg_grep("/pdf$|gif$|png$|jpg$|jed$/", $theFiles);
$output="";
foreach ($BookFiles as $currentFile) {
$output .= <<< Here
<ul>
<li><a href=MYBOOKS/$currentFile>$currentFile</a></li>
</ul>
Here;
}
$fp=fopen("BookIndex.htm","w");
fputs ($fp,$output);
fclose($fp);
readfile ("BookIndex.htm");
?>
来源:https://stackoverflow.com/questions/8613962/how-can-i-create-a-search-form-that-searches-files-in-a-folder