报错:PHP Warning: strpos(): Empty needle

2015年12月16日 | 分类: 【技术】

当不能连接WHOIS服务器时,报错:

PHP Warning:  strpos(): Empty needle in /.../whois.php on line 15

找到那一行PHP代码:

if( strpos($this->m_data[0], $this->m_serversettings[$this->m_servers[0]]['available']) === false ){

修改为:

if( ! empty($this->m_serversettings[$this->m_servers[0]]['available'] && strpos($this->m_data[0], $this->m_serversettings[$this->m_servers[0]]['available']) !== false) {
if (strpos($referrer['host'], $searcher) !== false) {
if ( ! empty($searcher) && strpos($referrer['host'], $searcher) !== false) {

A bunch of PHP search functions use the terms “needle” and “haystack” as their parameter names, indicating what is sought and where to seek it.

The strpos function is such a function. “Empty needle” means that you have passed in a null or empty value as the needle to look for. This is like saying “search for nothing” which doesn’t make sense to the function.

To fix this, check that the variable that you’re passing in as the needle has an actual value. The empty function is a good choice for that.

样例:

function akpc_is_searcher() {
        global $akpc;
        $referrer = parse_url($_SERVER['HTTP_REFERER']);
        $searchers = explode(' ', preg_replace("\n|\r|\r\n|\n\r", ' ', $akpc->searcher_names));
        foreach ($searchers as $searcher) {
                if (strpos($referrer['host'], $searcher) !== false) {
                        return true;
                }
        }
        return false;
}

修改为:

function akpc_is_searcher() {
        global $akpc;
        $referrer = parse_url($_SERVER['HTTP_REFERER']);
        $searchers = explode(' ', preg_replace("\n|\r|\r\n|\n\r", ' ', $akpc->searcher_names));
        foreach ($searchers as $searcher) {
                if ( ! empty($searcher) && strpos($referrer['host'], $searcher) !== false) {
                        return true;
                }
        }
        return false;
}

参考:《Warning: strpos(): Empty needle in …wordpress Plugin》
参考:《PHP – What does Warning: strpos() [function.strpos]: Empty delimiter in mean?》