My regular expression filter does not work

Asked

Viewed 29 times

1

I’m not getting the filter! when I put the negative sign appears ((entered and passed)) when shot appears passed however if I put strange characters it continues to show passed or n this 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";
?>
  • put the code in there so the guys can help you out

  • had put but forgot to put to execute

1 answer

2

First a tip, you don’t need isset if you’re 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 they all have the letter "A", so it will pass, because it is what your regex expects, that 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’s a md5 would be 0-9 and between a-f, but it is important to note that this does not validate anything, it just helps to check if it is a close format, should stay like this:

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

The ^ from the beginning, the $ from the end or to the end of the string and the {32} 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 function native to PHP that can check if it is hexadecimal, is the function ctype_xdigit, then 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";  
}
  • Yes, you need to use isset before empty yes. The function of isset is to check if there is that variable, the function of Empty is to check if THE ALREADY EXISTING VARIABLE is clean. If you use Empty on a GET Dice that doesn’t exist, it will return a notice.

  • @juniorb2ss does not need no, Empty does both, the way you did and "no" issues the Notice does not exist.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.