PHP 警告:strpos():search.php 中的空针

Cod*_*son 0 php

我有一个 php 搜索文件,它在目录中搜索具有提交名称的文件并显示结果。我想在与 php 代码相同的文件中使用 html 表单,即在 search.php 中仅像这样:

<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); 
?>
Run Code Online (Sandbox Code Playgroud)

但上面的代码给出了错误:Warning: strpos(): Empty needle in search.php on line 10

我尝试使用!empty这样的论点:

<?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); 
?>
Run Code Online (Sandbox Code Playgroud)

但它仍然反映了错误。

请帮助我消除这个错误。

u_m*_*der 5

您需要检查$q是否为空。如果它是空的 - 搜索有何意义。opendir如果为空,甚至不需要运行$q

if (!empty($q)) {
    $res = opendir($dir);
    while(false!== ($file = readdir($res))) { 
        // more codes here
Run Code Online (Sandbox Code Playgroud)