search
HomeBackend DevelopmentPHP TutorialThere is a misunderstanding in character judgment by strpos function in PHP_PHP Tutorial

There is a misunderstanding in character judgment by strpos function in PHP_PHP Tutorial

Jul 13, 2016 am 10:45 AM
phpstrposAppearfunctionjudgmentexistcharacterstringexistyesFindofMisunderstandingfirst

In php, strpos is the position where the string first appears. If it exists, it will return true or related specific numbers. If not, it will return 0 or false. But I want to use it to make a wordpress keyword blacklist to anti-spam comments. Found some problems, let's take a look below.

Modify the theme comments-ajax.php file

In the comments-ajax.php file in the theme directory, it is about line 60 (just get the $_POST['author'] and other fields in the comment form submitted by the user). Then add the following code to the file:

The code is as follows Copy code
 代码如下 复制代码

    /*
    * @Author: vfhky 2013年09月21日22:13
    * @Variable string $word: 黑名单中的关键词,用户可自行按规律进行增加或减少
    * @Variable string $comment_author: 用户提交的$_POST['author']字段值,表示昵称
    * @Variable string $comment_content: 用户提交的$_POST['comment']字段值,表示评论内容
    **/
    $words = "com,cn,info,net,www,http,cc,host,代理,移动,电,国,港,器,服,医,肥,药,农,信,贷,日,盈,网,票,域,销,黄,司,企,机,租,人,钱,设,购,播";
    $word = explode(',', $words);
    $num = count($word);
    for($i=0;$i     if (strpos($comment_author,$word[$i],0) || strpos($comment_content,$word[$i],0)){
    err( __('广告必删,多谢理解!') );
    break;
    }
    }

/*
* @Author: vfhky September 21, 2013 22:13
* @Variable string $word: Keywords in the blacklist, users can increase or decrease them according to rules
* @Variable string $comment_author: The $_POST['author'] field value submitted by the user, indicating the nickname
* @Variable string $comment_content: The $_POST['comment'] field value submitted by the user, indicating the comment content
​ **/
$words = "com,cn,info,net,www,http,cc,host,agent,mobile,electricity,country,Hong Kong,equipment,service,medicine,fertilizer,medicine,agriculture,credit,loan,day,profit, Internet, ticket, domain, sales, yellow, company, enterprise, machine, rent, people, money, equipment, purchase, broadcast";
$word = explode(',', $words);
$num = count($word);
for($i=0;$i If (strpos($comment_author,$word[$i],0) || strpos($comment_content,$word[$i],0)){
err( __('Advertising must be deleted, thank you for your understanding!') );
Break;
}
}

4 Postscript

Through the above simple code, we have realized the verification of the keywords in the blacklist by submitting the user nickname and comment content entered in the comment. Once any of the above words is matched, for example, www appears, the user will be prompted "The advertisement must be deleted, thank you for your understanding!" The effect is as shown in the figure below. This is another insurance for the blog, which enhances the immunity of WordPress against spam comments, and it is also achieved through a non-plugin method!

There is a misunderstanding in character judgment by strpos function in PHP_PHP TutorialThe above looks fine, but this morning @Bad Children’s Shoes did an evil test and discovered a bug in the code of the previous article. When I came back from get off work in the evening, I looked at the code carefully and found that I had a one-sided understanding of the strpos function, so I made a note to mark it.

2 Prototype of strpos function

I believe everyone is familiar with the strpos function, and it can often be seen in string processing. The strpos function prototype is:

/*
* @Para string $source: Search in this string [*]
* @Para mixed $target: The string to be found; if it is not a string, it will be converted to an integer and regarded as the sequential value of characters [*]
* @Para int $offset: starting position of search
* @Return int/boolean: If successful, return the position of the first occurrence; if failed, return FALSE value
​ **/
int strpos(string $source, mixed $target [, int $offset = 0 ]);
 

3 Simple test of strpos function

After understanding the prototype of the strpos function, let’s first look at a simple test code.

The code is as follows Copy code
/*
 代码如下 复制代码
  /*
    * @Author: vfhky 2013年09月21日20:35
    * @Description: 通过两个不同的测试变量$test_1和$test_2直击关键
    **/
        $words = "com,cn,info,net,www,http,cc,host,代理,移动,电,国,港,日,购";
    $word = explode(',', $words);
    $num = count($word);
    $test_1 = "购买TT";
    for($i=0;$i     if (strpos($test_1,$word[$i],0)){
    echo '广告必删,多谢理解!';
    break;
    }
    }
    echo "

----------This is $test_1 END----------

";
    
    $test_2 = "坏坏购买TT";
    for($i=0;$i     if (strpos($test_2,$word[$i],0)){
    echo '广告必删,多谢理解!';
    break;
    }
    }
    echo "

----------This is $test_2 END----------

";
    ?>
* @Author: vfhky September 21, 2013 20:35 * @Description: Hit the key point directly through two different test variables $test_1 and $test_2 ​ **/ $words = "com,cn,info,net,www,http,cc,host,agent,mobile,electric,country,Hong Kong,Japan,shopping"; $word = explode(',', $words); $num = count($word); $test_1 = "Buy TT"; for($i=0;$i If (strpos($test_1,$word[$i],0)){ echo 'The advertisement must be deleted, thank you for your understanding!'; Break; } } echo "

----------This is $test_1 END----------

​   $test_2 = "Buy TT badly"; for($i=0;$i If (strpos($test_2,$word[$i],0)){ echo 'The advertisement must be deleted, thank you for your understanding!'; Break; } } echo "

----------This is $test_2 END----------

?>

The test results are shown below:

There is a misunderstanding in character judgment by strpos function in PHP_PHP Tutorial

Re-discuss WordPress anti-spam comments: It’s all the fault of the strpos function


4 Analysis of test results of strpos function

There are two different test variables $test_1 and $test_2 in the above code, and both of them contain the keywords in the blacklist: purchase. However, judging from the test results shown in the figure, the $test_1 variable is not effectively blocked, while the variable $test_2 is prompted to contain advertising words. The secret lies in the position where the word "purchase" appears in variables $test_1 and $test_2! When the keyword "purchase" appears at the front ($test_1), the execution result of the strpos($test_1,$word[$i],0) function is 0, because the word "purchase" is in the string "purchase TT" The front. Then the if statement in the for loop becomes if(0){}, so that it will not be regarded as a spam comment, which causes a BUG. The following are two methods to implement "wordpress keyword blacklist: anti-spam comment upgrade" by continuing to use the strpos function and using PHP regular expressions.
5.1 Correctly use strpos function to fix BUG

The code is as follows Copy code
 代码如下 复制代码

    /*
    * @Author: vfhky 2013年09月24日20:06
    * @Description: 正确使用strpos函数,解决上一篇文章代码的BUG
   
    **/
    $words = "com,cn,info,net,www,http,cc,host,代理,移动,电,国,港,器,服,医,肥,药,农,信,贷,日,购,播";
    $word = explode(',', $words);
    $num = count($word);
    for($i=0;$i     if ( (strpos($comment_author,$word[$i],0) !== false) || (strpos($comment_content,$word[$i],0) !== false) ){
    err( __('广告必删,多谢理解!') );
    break;
    }
    }

/*

* @Author: vfhky September 24, 2013 20:06

* @Description: Use the strpos function correctly to solve the bug in the code of the previous article

 

​ **/
 代码如下 复制代码
/*
    * @Author: vfhky 2013年09月24日20:06
    * @Description: 使用PHP正则表达式修正BUG,实现“There is a misunderstanding in character judgment by strpos function in PHP_PHP Tutorial”
  
    **/
    $words = "com,cn,info,net,www,http,cc,host,代理,移动,电,国,港,器,服,医,肥,药,农,信,贷,日,购,播";
    $word = explode(',', $words);
    $num = count($word);
    for($i=0;$i     if( preg_match("/$word[$i]/i", $comment_author) || preg_match("/$word[$i]/i", $comment_content) ){
    err( __('广告必删,多谢理解!') );
    break;
    }
    }
$words = "com,cn,info,net,www,http,cc,host,agent,mobile,electricity,country,Hong Kong,equipment,service,medicine,fertilizer,medicine,agricultural,credit,loan,Japan,purchase, broadcast"; $word = explode(',', $words); $num = count($word); for($i=0;$i If ( (strpos($comment_author,$word[$i],0) !== false) || (strpos($comment_content,$word[$i],0) !== false) ){ err( __('Advertising must be deleted, thank you for your understanding!') ); Break; } }
5.2 Use PHP regular expressions to fix BUG
The code is as follows Copy code
/* * @Author: vfhky September 24, 2013 20:06 * @Description: Use PHP regular expressions to correct BUG and implement "wordpress keyword blacklist: anti-spam comments and upgrade (non-plugin)" ​ **/ $words = "com,cn,info,net,www,http,cc,host,agent,mobile,electricity,country,Hong Kong,equipment,service,medicine,fertilizer,medicine,agricultural,credit,loan,Japan,purchase, broadcast"; $word = explode(',', $words); $num = count($word); for($i=0;$i If( preg_match("/$word[$i]/i", $comment_author) || preg_match("/$word[$i]/i", $comment_content) ){ err( __('Advertising must be deleted, thank you for your understanding!') ); Break; } }

6 Important reminders about function strpos

Another thing to note when using the strpos function is that it may return a Boolean value of FALSE, but it may also return a non-Boolean value equivalent to FALSE.
For example, return integer type 0, floating point value 0.0, empty string, string "0", array not including any elements, object not including any member variables, special type NULL, etc.
Therefore, the return value of this function should be tested using the identity operator "===" which checks the type of the returned value, rather than using the simple equal sign "==".

7Update 2013.09.26 22:27

After being reminded by @星河大帝, you can use an array instead of a string, and the execution efficiency should be about the same.
7.1 Use strpos function + array to fix BUG

The code is as follows Copy code
 代码如下 复制代码

    $words = array("com","cn","info","net","www","http","cc","host","代理","移动","电","国","港","购");
    $num = count($words);
    for($i=0;$i     if (strpos($comment_author,$words[$i],0) !== false || strpos($comment_content,$words[$i],0) !== false){
    err( __('广告必删,多谢理解!') );
    break;
    }
    }

$words = array("com","cn","info","net","www","http","cc","host","agent","mobile","电竞", "country", "Hong Kong", "purchase");

$num = count($words);

for($i=0;$i If (strpos($comment_author,$words[$i],0) !== false || strpos($comment_content,$words[$i],0) !== false){ err( __('Advertising must be deleted, thank you for your understanding!') );
 代码如下 复制代码
  $words = array("com","cn","info","net","www","http","cc","host","代理","移动","电","国","港","购");
    $num = count($words);
    for($i=0;$i     if( preg_match("/$words[$i]/i", $comment_author) || preg_match("/$words[$i]/i", $comment_content) ){
    err( __('广告必删,多谢理解!') );
    break;
    }
    }
Break;

}

}

7.2 Use regular expressions + arrays to fix BUG

The code is as follows Copy code
$words = array("com","cn","info","net","www","http","cc","host","agent","mobile" ,"Electricity","Country","Hong Kong","Purchase"); $num = count($words); for($i=0;$i If( preg_match("/$words[$i]/i", $comment_author) || preg_match("/$words[$i]/i", $comment_content) ){ err( __('Advertising must be deleted, thank you for your understanding!') ); Break; } }
http://www.bkjia.com/PHPjc/633054.html
www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633054.htmlTechArticleIn php, strpos is the position where the string first appears. If it exists, it returns true or the relevant specific number, no It will return 0 or false, but I want to use it to make a wordpress keyword blackname...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version