PHP - Valid DNS name


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function isValidDomain($value) {
  2. if($value) {
  3. //Max 255 chars
  4. if(strlen($value) > 255) {
  5. return false;
  6. }
  7. //Remove trailing .
  8. if(substr($value,-1,1) == '.') {
  9. $value = substr($value,0,-1);
  10. }
  11. $labels = explode('.',$value);
  12. //More than 2 labels
  13. if(count($labels) >= 2) {
  14. foreach($labels as $label) {
  15. //Cannot start or end with a -
  16. if(substr($label,0,1) == '-' || substr($label,-1,1) == '-') {
  17. return false;
  18. }
  19. //Allowed characters a-z, 0-9, -
  20. if(!preg_match('/^[a-z\d-]{1,63}$/i',$label)) {
  21. return false;
  22. }
  23. }
  24. } else {
  25. return false;
  26. }
  27. return true;
  28. }
  29. return false;
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.