My filter with regular expressions does not work

1

I can not do the filter! when I put the negative sign appears ((entered and passed)) when shooting appears passed by if I put strange characters it continues to show passed or is not filtering!

<?php
    //$_GET['h'] vem em md5
    if(!isset($_GET['h']) || empty($_GET['h'])){
?>
    <script type="text/javascript"> window.location.href = "http://localhost/site/"</script>
<?php  
        exit();
    }

    if(!preg_match("/\w/", $_GET['h'])){
        echo"entrou";  
    }
    echo "passou";
?>
    
asked by anonymous 21.12.2017 / 15:09

1 answer

2

First a tip, you do not need isset if already using empty , just do this:

 if (empty($_GET['h'])) {

Your regex is using \w which is equivalent to doing this [A-Za-z0-9_] , however its regex does not state where it begins and where it ends, anything like:

  • +a
  • :a
  • ;a
  • "a
  • &a

Note that it has strange characters, but everyone has the letter "A", so it will pass, because that is what your regex expects, that it has any letter, even if it has a series of strange characters and is in any string position see the test:

var x = [
    'foo bar +a foo bar',
    'foo bar :a',
    'foo bar ;a',
    '"a',
    '&a foo bar'
];

var regex = /\w/;

for (var i = 0, j = x.length; i < j; i++) {
    console.log(x[i], '=>', regex.test(x));
}

See that all returned TRUE

Now if you want to check if it is a md5 would be 0-9 and enter af, only it is important to note that this does not validate anything, it only helps to check if it is a close format and should look like this:

^[a-f\d]{32}$

% of% checks from the beginning, ^ checks from the end or the end of the string and $ checks if it has 32 characters.

Your whole code would look like this:

<?php
    //$_GET['h'] vem em md5
    if(empty($_GET['h'])){
?>
    <script type="text/javascript"> window.location.href = "http://localhost/site/"</script>
<?php  
        exit;
    }

    if(!preg_match("^[a-f\d]{32}$", $_GET['h'])){
        echo"entrou";  
    }

    echo "passou";
?>

However, it is important to note that the characters generated in an MD5 are hexadecimal (a-f0-9), ie there is a native PHP function that can check if it is hexadecimal, {32} , so just know if the string has 32 characters, it should look like this:

$h = $_GET['h'];

if (strlen($h) === 32 && ctype_xdigit($h)) {
    echo"entrou";  
}
    
21.12.2017 / 15:29