Re: Check a string does not contain invalid characters

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, March 21, 2007 11:15 pm, John Comerford wrote:
> I want to accept a character string which I will use as a unique user
> id.  I want to check the string to ensure the user has not typed
> characters that I consider to be invalid as part of a user id.  I was
> thinking of doing something along the lines of:
>
> if (strpbrk($userid, '~!@#$%^&*()_+=-{}[]\\|;\':"<>?,./`') <> null) {
> blah, blah, blah......
>
> but I think that would still leave me open to control characters.
> I am thinking maybe I should loop through the string character by
> character and check it's ascii value (using ord) is within the range
> of
> a-z and A-Z ?
> Is this the best way of achieving this ?  Is there a php command to do
> something similar ?  I have done a few web searches and haven't come
> up
> with much.

You do not want to "blacklist" certain characters and, as you have
noticed, miss the control characters or something you didn't think of.

You want to "whitelist" the characters that you DO accept.

Something like this:

if (!preg_match('|^[a-z0-9_-]+$|i', $username)){
  echo "INVALID USERNAME!";
}

-- 
Some people have a "gift" link here.
Know what I want?
I want you to buy a CD from some indie artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux