strpos(): 空针 WordPress 插件

strpos(): Empty needle WordPress Plugin

我刚刚完成了我的第一个插件的构建,并在我的个人网站上使用各种插件对其进行了测试,没有出现任何错误。然而,一些用户表示该插件导致他们出现以下错误:

strpos(): Empty needle in /west/XXXXX/public_html/wp-content/plugins/bot-block/bot-plugin.php on line 200

在第 200 行我有这个:

            //See if the domain that referred is in the current block url
            $pos = strpos( $referrer, $site );

现在我看不出那条线有什么问题,所以我会给你整个功能:

//Check referrer function
function bot_block_parse()
{
    //Get the options for the plugin
    $options = get_option( 'bot_block' );

    //See if the request was from another site
    if( isset( $_SERVER['HTTP_REFERER'] ) )
    {
        //Split the URL into it's components
        $referrer = parse_url( $_SERVER['HTTP_REFERER'] );

        //Trim the components
        $referrer = array_map( 'trim', $referrer );

        //Get the domain name
        $referrer = $referrer['host'];

        //Get the block list
        $list = $this->create_block_list();

        //Loop through all the blocked domains
        foreach( $list as $site )
        {
            //Trim the domain
            $site = trim( $site );

            //Set the prefix for domains that aren't sub domains
            $prefix = 'www';

            //Split domain into smaller components
            $domainParts = explode( ".", $referrer );

            //See if the domain that referred is in the current block url
            $pos = strpos( $referrer, $site );

            //See if block subdomains is checked
            if( isset( $options['subdomains'] ) )
            {
                //Check to see if the domain was the current blocked site and if the prefix is not www
                if( $pos !== false && $domainParts[0] != $prefix )
                {
                    //Log spam
                    $this->log_spam( $site );

                    //Call the redirect function to see where to send the user
                    $this->bot_block_redirect();
                    exit;
                }
            }

            //See if the domain was the current site blocked and the prefix is www
            if( $pos !== false && $domainParts[0] == $prefix )
            {
                //Log spam
                $this->log_spam( $site );

                //Call the redirect function to see where to send the user
                $this->bot_block_redirect();
                exit;
            }
        }
    }
}

如果您需要查看完整的插件代码,我已将其放在此处的 pastebin 中:http://pastebin.com/gw7YbPVa

谁能帮我解决这个问题?

快速解决方法是在尝试调用 strpos() 之前查看您的针头 ($site) 是否为空。如果为空,肯定大海捞针找不到,干脆跳过,把$pos设为false。

$pos = strpos( $referrer, $site );

变为:

if ( $site == '' || !$site ) {
   $pos = false;
} else {
   $pos = strpos( $referrer, $site );
}

更好的解决方案是首先确定 $site 变量为什么为空。 $list 数组中的每个子元素是否包含另一个数组,而不是您期望的字符串?您可以在循环中使用 var_dump( $site ); 来查看该变量的内容。