Posted By

peckham on 03/14/11


Tagged

url php validation


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

janwebdev


PHP URL validation


 / Published in: PHP
 

This function can be used to validate an URL

  1. <?php
  2.  
  3. function isValidURL($value) {
  4.  
  5. $value = trim($value);
  6. $validhost = true;
  7.  
  8. if (strpos($value, 'http://') === false && strpos($value, 'https://') === false) {
  9. $value = 'http://'.$value;
  10. }
  11.  
  12. //first check with php's FILTER_VALIDATE_URL
  13. if (filter_var($value, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) === false) {
  14. $validhost = false;
  15. } else {
  16. //not all invalid URLs are caught by FILTER_VALIDATE_URL
  17. //use our own mechanism
  18.  
  19. $host = parse_url($value, PHP_URL_HOST);
  20. $dotcount = substr_count($host, '.');
  21.  
  22. //the host should contain at least one dot
  23. if ($dotcount > 0) {
  24. //if the host contains one dot
  25. if ($dotcount == 1) {
  26. //and it start with www.
  27. if (strpos($host, 'www.') === 0) {
  28. //there is no top level domain, so it is invalid
  29. $validhost = false;
  30. }
  31. } else {
  32. //the host contains multiple dots
  33. if (strpos($host, '..') !== false) {
  34. //dots can't be next to each other, so it is invalid
  35. $validhost = false;
  36. }
  37. }
  38. } else {
  39. //no dots, so it is invalid
  40. $validhost = false;
  41. }
  42. }
  43.  
  44. //return false if host is invalid
  45. //otherwise return true
  46. return $validhost;
  47. }
  48.  
  49. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: hippomegas on March 14, 2011

Nice, clean... thank you

You need to login to post a comment.