0

I have a working code to restrict & validate subdomain.

 $exp = explode('.', 'blog.mydomain.my.');

 print_r($exp);
 if(count($exp) == 3 && $exp[1] == "mydomain" && $exp[2] == "my" || $exp[3] == "") {
    echo "<br>";
  echo 'subdomain valid';
 } else{
    echo "<br>";
  echo 'not valid';
 }

now it need to check if its only false and I'm not so sure about the $exp[3] != "" comparison. From example below the subdomain should be valid but it give me error.

 echo "<br>";echo "<br>";
 $exp2 = explode('.', 'blog.mydomain.my.');

 print_r($exp2);
 if(count($exp2) != 3 || $exp2[1] != "mydomain" || $exp2[2] != "my" || $exp[3] != "") {
    echo "<br>";
  echo 'not valid';
 }

Accepted numbers of subdomain is hello.mydomain.my or hello.mydomain.my. (with trailing dot). While hello.world.mydomain.my is not accepted.

Thanks in advance

2
  • what is the error exactly ? Is the code not working ? Commented Aug 2, 2013 at 18:03
  • I feel like either you should be checking if count($exp2) != 4 or you should take off the last condition, as if the count is 3 the last condition should go out of bounds Commented Aug 2, 2013 at 18:06

2 Answers 2

2

This should give you what you want.

if(count($exp2) < 3 || count($exp2) > 4 || $exp2[1] != "mydomain" || $exp2[2] != "my" || (count($exp2) != 4 && $exp[3] != "")) {
  echo "<br>";
  echo 'not valid';
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why not regex? $valid = preg_match('/^hello\.domain\.my\.?$/', $domain) ? true : false;
@AlexP with a different subdomain pattern that would work as well. You should refine and post that as an answer...I would upvote
just to understand your code.. subdomain will be not valid if ONE of the statement match the criteria and to be valid all statement must not match the criteria?
2

I would go for a regex solution, possibly even encapsulate it in a function:

function isValidDomain($domain) 
{
  return preg_match('/^[\w]+\.(mydomain)\.(my)\.?$/', $domain) ? true : false;
}

var_dump(isValidDomain('www.google.com'));
var_dump(isValidDomain('test.invalid.domain'));
var_dump(isValidDomain('hello.mydomain.my'));
var_dump(isValidDomain('hello.mydomain.my.'));

2 Comments

I think the intent was for any subdomain to match so maybe '/^[\w]+\.(mydomain)\.(my)\.?$/'
Yes any subdomain to match with my domain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.