duanqinqiao4844 2016-05-16 02:49
浏览 66
已采纳

php strpos没有返回任何值

So, my website is getting a significant amount of spam.

To filter out some of it, I wanted to test the body of the post to make sure it doesn't contain certain words. If they do, give the user an instant (temporary) ban.

Included is my code. I added an echo line to show the position returned, and tested with posts which did or did not include test words. For whatever reason, it always returns null, and nothing is displayed. Am I not allowed to pass a $_POST variable into this function?

Code:

    $bannedwords = array ("spam word", "foo", "bar", "foobar", "quarry");
foreach ($bannedwords as $bannedphrase) {
    $pos = strpos($_POST['body'], $bannedphrase);
    echo 'The position is: ' . $pos;
    if ($pos === FALSE){            
        //require_once 'inc/mod/ban.php';
        //Bans::new_ban($_SERVER['REMOTE_ADDR'], 'Suspected Spammer.', '2', $_POST['board'] == '*' ? false : $_POST['board']);
        error($config['error']['bannedword']);
    }       
}

EDIT: I do see a logic error here, though I don't think its what breaks the code. Maybe it is, however. If a user is banned early into the array, the if statement continues, which could be the reason I am seeing a null value later on?

  • 写回答

2条回答 默认 最新

  • dpno17028 2016-05-16 03:32
    关注

    As others have pointed out, you're testing the value backwards, since strpos will only return FALSE if the search string was NOT found. Also, echo your POST variable before you search it to make sure it is what you think it is.

    Try this code:

    $bannedwords = array ("spam word", "foo", "bar", "foobar", "quarry");
    
    if (isset($_POST['body'])) { echo 'POST: ', $_POST['body'], '<br/>'; }
    else { echo 'No POST variable found!'; }
    
    foreach ($bannedwords as $bannedphrase) 
    {
        $pos = strpos($_POST['body'], $bannedphrase);
    
        if ($pos === FALSE)
        {
            echo '  Banned word not found.';
        }
        else
        {
            echo '  Banned word found at position: ', $pos;
    
            //require_once 'inc/mod/ban.php';
            //Bans::new_ban($_SERVER['REMOTE_ADDR'], 'Suspected Spammer.', '2', $_POST['board'] == '*' ? false : $_POST['board']);
    
            error($config['error']['bannedword']);
            break; // This will exit the foreach loop
        }       
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?