hi, I havent used php in a long time so i'm more than a little rusty and i'm having some trouble that i cant seem to figure out on my own so i figured i'd ask the experts.

I have a registration form that gets filled out on one page and calls a php script. This script checks to make sure everything is good (length requirements and invalid characters, passwords match, etc.) but i'm having difficulty checking for invalid characters

The username from the form goes to $_POST['username'] and from there gets set back to $username

$numberoferrors is a variable that increases with each problem found
and if it is 0 by the end of the script it will add the entry to the mysql database

and then i check it with this:

//only letters numbers and an underscore are allowed
if(preg_match("/[^a-zA-Z0-9\_]+$/s", $username))
{
  ++$numberoferrors;
  echo "Error: Username contains invalid characters<br>";  
}

My problem is that some invalid usernames dont trigger the error.

Most of the time it will catch it but certain usernames dont trigger the error.

One of these usernames would be "O\/\/L" without the quotes

and for some reason the username variable shows "\" for every "\" typed in the username section of the form. (thats 2 slashes for every one slash you actually typed) so it actually gets sent to the php script as "O\/\/L"

putting the username in as "\/\/" triggers the error as well as "O\/\/" but "O\/\/L" seems to avoid triggering the error for some reason. I only want letters (upper and lower case), numbers, and an underscore.....no other characters should be allowed not even spaces.

Any help would be greatly appreciated

    I thought the "$" was paired up with the "" and needed at the end of the pattern. I don't doubt that your write tho because that would explain why it was working sometimes and not the others and why adding that "L" at the end prevented it from tripping the error...I'm just not 100% sure what the "" "+" and the "$" are for. Thanks alot tho....that was quick.

    Just tried it and.....

    It didn't work I removed the "+$" and now it allows anything to be entered in, nothing triggers an error for invalid characters.

      Drop the "+$" from the end. With that there the pattern will only match if the username ends with one or more invalid characters. You want it to match if there are any invalid characters (and you don't care if there might be more than one) anywhere.

        Thankyou very much....I incorrectly thought your solution didn't work at first because i moved a section of code to a different area along with the line that sets the $username variable....after I put that line of code back at the top where it belonged it worked perfectly....so thankyou very much 😃

          Write a Reply...