Jump to content

Filtering Input


N-Bomb(Nerd)

Recommended Posts

Hello, I've never really been good at filtering user input. I guess I've never really tried to use it so much in fear of getting hacked or something. Anyways, I'm trying to make a script that will take a users input and create a directory on my sever from what they named it. However, how would I be able to run a "check" for all symbols/spaces/quotes? I don't want them to submit it and just have the script create the directory without something they put in the name of it.. so I kind of want it to scan for anything pretty much that isn't alpha-numeric with the exception of one underscore that isn't at the start or end of the name. How would one accomplish such thing?

 

I could probably spend a few hours and mess around with this and figure out a separate way to do each one of these rules, but I've never really figured out how to sort of put different things together. Would anyone be willing to show me that as well.. that way at least I could turn this into a learning experience instead of someone just responding with just the answer.

Link to comment
Share on other sites

if(!preg_match("~^[a-zA-Z0-9]\w*[a-zA-Z0-9]$~",$val,$match)) {
   // not valid
}

 

^ start of string (so first char must be an [a-zA-Z0-9])

[a-zA-Z0-9] match 1 character that is a letter or number (no underscore)

\w* match 0 or more alphanumeric characters (number, letter, underscore)

[a-zA-Z0-9] match 1 character that is a letter or number (no underscore)

$ end of string (so last char must be an [a-zA-Z0-9])

 

Basically it says to start at the beginning of the string, only match if the first character is a letter or number, then match any amount of numbers, letters, or underscores, all the way to the end of the string.  But then it has to match only a letter or number at the end of the string, so the * gives up the last char to see if that last [..] matches.  If it doesn't, regex fails.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.