Im making a simple search on my website for files in directory.
All files in it looks like example.html
.
I already made that user can't search empty input and i wan't to prevent user from searching all that is in $exclude
string. Otherwise if user will type in example dots, it will show every file that is in directory.
Here is my php code:
$dir = "data/pages/";
$exclude = array('.','..','.htaccess','index');
if(array_key_exists('submit', $_POST)) {
if (empty($_POST['field1'])) {
echo("<p><h3>Please fill all the fields</h3>");
}
else {
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
echo("<p><h3>↓Search Results↓</h3>");
while (($file = readdir($dh)) !== false) {
$filename = pathinfo($file, PATHINFO_FILENAME);
if(preg_match("/{$_POST['field1']}/i", $filename) &&!in_array($file,$exclude)) {
echo("<p>Found: <b><a href=\"https://mywebsite.wtf/data/pages/" . $file . "\">$filename</a>");
}
}
closedir($dh);
}
}
}
}
CodePudding user response:
depending of the match (exact match or contain), you can do that:
if input contain some exclude:
$isOk = true;
$exclude = ['.','..','.htaccess','index'];
foreach ($exclude as $exclude){
if(str_contains($_POST['field1'], $exclude)){
$isOk = false;
}
}
if input contain some exact input
$isOk = true;
$exclude = ['.','..','.htaccess','index'];
if(in_array($_POST['field1'], $exclude, true)){
$isOk = false;
}
In your code, with exact check:
$dir = "data/pages/";
$excludes = array('.','..','.htaccess','index');
$isOk = true;
if(in_array($_POST['field1'], $excludes, true)){
$isOk = false;
}
if(array_key_exists('submit', $_POST)) {
if (empty($_POST['field1'])) {
echo("<p><h3>Please fill all the fields</h3>");
}
if (!$isOk) {
echo("<p><h3>You cannot search that!</h3>");
}
else {
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
echo("<p><h3>↓Search Results↓</h3>");
while (($file = readdir($dh)) !== false) {
$filename = pathinfo($file, PATHINFO_FILENAME);
if(preg_match("/{$_POST['field1']}/i", $filename) &&!in_array($file,$exclude)) {
echo("<p>Found: <b><a href=\"https://mywebsite.wtf/data/pages/" . $file . "\">$filename</a>");
}
}
closedir($dh);
}
}
}
}