strpos(): Плагин WordPress для пустой иглы

Я только что закончил создание своего первого плагина и протестировал его с различными плагинами на своем личном сайте без ошибок. Однако некоторые пользователи говорят, что плагин вызывает у них следующие ошибки:

strpos(): пустая игла в /west/XXXXX/public_html/wp-content/plugins/bot-block/bot-plugin.php в строке 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

Может ли кто-нибудь помочь мне понять это, пожалуйста?


person RuFFCuT    schedule 23.02.2016    source источник
comment
Ваш параметр пуст, поэтому он выдает ошибку, вы должны отлаживать эти переменные, прежде чем использовать их, чтобы избежать подобных проблем.   -  person Marcos Pérez Gude    schedule 23.02.2016


Ответы (1)


Быстрое решение состоит в том, чтобы проверить, пуста ли ваша игла ($site), прежде чем пытаться позвонить strpos(). Если он пуст, то его точно нельзя найти в стоге сена, поэтому мы должны вообще пропустить его и установить $pos в false.

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

Становится:

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

Лучшее решение — сначала определить, почему ваша переменная $site пуста. Содержит ли каждый дочерний элемент в массиве $list другой массив вместо строки, как вы ожидаете? Вы можете использовать var_dump( $site ); в своем цикле, чтобы увидеть содержимое этой переменной.

person Patrick Moore    schedule 23.02.2016
comment
Спасибо, я также хотел бы знать, почему он пуст, но я не могу воспроизвести проблему :( - person RuFFCuT; 23.02.2016
comment
@RuFFCuT, как это часто бывает. Но, по крайней мере, с помощью этой логики вы можете обнаружить и избежать возникновения ошибки. :} - person Patrick Moore; 23.02.2016