phpsecurityfiltertextareamessage

Using PHP to check if there are unsuitable characters in a textarea form


The $handle is given the value of '1' even if there are no characters in the text area which appear in the array.


$handle = '';
$message 'nothing in here except plain text';


        // check message doesnt contain odd characters
        $check = 'href,http,#,¥,²,æ,é,Hello. And Bye.,£,$,ˆ,ª,³,¦,½,å,œ,…,§,¾,‡,»,ç,º,³,ä,¿,Â,¶,¸,µ,Ž,°,Œ,Å,’,€,â,¢,¬,ƒ,Æ,†,±,š,¡,Ñ,‘,Ë,‹,¹,·,Þ,`';
        
        $check = explode(",", $check);

        $num = count($check);
        
        $num = $num + 1;
        
        $count = 0;

        while ($count < $num) {
            
            if (strpos($message,$check[$count]) !== false) {
            $handle = 1; break;
            }
            
            $count++;
        }

Solution

  • Here is the improved, bug-free version of your code.

    Bugs

    1. In $message, the = sign is missing between $message and string 'nothing in here except plain text'.

    2. $handle is set as an empty string (''), but it’s better to use 0 or boolean false.

    3. Adding 1 to $num was unnecessary and could cause an error.

    4. The original code was a bit confusing. It can be improved for clarity and better flow.

    Improvements:

    <?php
        $handle = 0;
        $message = 'nothing in here except plain text href';
        
        // Check message doesn't contain odd characters
        $checkChars = 'href,http,#,¥,²,æ,é,Hello. And Bye.,£,$,ˆ,ª,³,¦,½,å,œ,…,§,¾,‡,»,ç,º,³,ä,¿,Â,¶,¸,µ,Ž,°,Œ,Å,’,€,â,¢,¬,ƒ,Æ,†,±,š,¡,Ñ,‘,Ë,‹,¹,·,Þ,`';
        $checkArray = explode(",", $checkChars);
        
        foreach ($checkArray as $char) {
            if (strpos($message, $char) !== false) {
                $handle = 1;
                break;
            }
        }
        
        echo $handle;
    

    Online Demo