• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 889
  • Last Modified:

Filtering / sanitizing an input (domain) for PHP

One of my scripts receives a user-input value "name" that will serve as a domain or subdomain, hence I must make sure it contains only allowed characters, and must replace the rest.

My rules are as follows for that name that arrives in lower case:
- name must only contains A-Z (or a-z but converted earlier) or dots, anything else must be deleted to avoid cross-site scripting
- it may contain 1 or 2 dots (name.fr or name.co.uk) and if so must be flagged as a domain, but dots cannot be at the beginning, the end, or a dot follow another dot (ie usual domain rules)
- If the final value is a word only then I add .samplename.com at the end
- else the name is a doman and is used as such

I already have a good email validation test:

eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$', $email)

 but it just returns an error if the email does not pass, here I must convert the chain.
Which PHP rules would help me do the above ?

  • 2
  • 2
1 Solution
DenisvtAuthor Commented:
I guess this is very as this rule validates a domain, but how would I go about replacing all other unallowed characters if found in the chain ?

preg_match ("/^(([a-z0-9][-a-z0-9]*?[a-z0-9])\.)+[a-z]{2,6}$/", $domain)
Terry WoodsIT GuruCommented:
Something like this?

$name = preg_replace("/[^a-z\d.]/","",$name); #remove unacceptable chars

Note though that I think there are a whole heap of characters acceptable in domain names that you would be removing. It might meet your needs anyway though.
Ray PaseurCommented:
"a good email validation test" might be better if you used the built-in PHP function.  This should get you started.

Domain names are not case-sensitive (nor are email addresses).  HTH, ~Ray
DenisvtAuthor Commented:
It seems preg_replace("/[^a-z\d.]/","",$name); does the job, not sure which allowed chars it could remove ?
Domain names case does not matter indeed, I was just lowering it to not have to test whether upper case letters were found.
I was not aware of that PHP function, will have a look thanks.
Ray PaseurCommented:
Yeah, the whole question of filtering and validating data fields has sort of "been done" before.  Good luck with your project, ~Ray
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now