I have a php search file that searches a directory for files with the submitted names and displays the results. I want to use the html form in the same file as the php code i.e., in search.php only like this:
<form action="search.php" method="get"><input name="q"
type="text"> <input type="submit"></form>
<?php
$dir = '/www/posts';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude))
{
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
echo "<a href='$withoutExt'>$withoutExt</a>";
echo "<br>";
}
}
closedir($res);
?>
But the above code gives the error : Warning: strpos(): Empty needle in search.php on line 10
I tried using the !empty
argument like this:
<?php
$dir = '/www/posts';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
$res = opendir($dir);
if (!empty($res)) {
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
echo "<a href='$withoutExt'>$withoutExt</a>";
echo "<br>";
}
else {
echo "";
}
}
}
closedir($res);
?>
But it still reflects the error.
Please help me get rid of this error.