PHP Saber si una URL es correcta


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



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function is_valid_url($url)
  4. {
  5. $url = @parse_url($url);
  6.  
  7. if (!$url)
  8. {
  9. return false;
  10. }
  11.  
  12. $url = array_map('trim', $url);
  13. $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
  14. $path = (isset($url['path'])) ? $url['path'] : '';
  15.  
  16. if ($path == '')
  17. {
  18. $path = '/';
  19. }
  20.  
  21. $path .= (isset($url['query'])) ? "?$url[query]" : '';
  22.  
  23. if (isset($url['host']) AND $url['host'] != gethostbyname($url['host']))
  24. {
  25. if (PHP_VERSION >= 5)
  26. {
  27. $headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
  28. }
  29. else
  30. {
  31. $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
  32.  
  33. if (!$fp)
  34. {
  35. return false;
  36. }
  37. fputs($fp, "HEAD $path HTTP/1.1
  38. Host: $url[host]
  39.  
  40. ");
  41. $headers = fread($fp, 4096);
  42. fclose($fp);
  43. }
  44. $headers = (is_array($headers)) ? implode("\n", $headers) : $headers;
  45. return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
  46. }
  47. return false;
  48. }
  49.  
  50. ?>
  51. <?php
  52.  
  53. if (is_valid_url('http://www.secondversion.com'))
  54. {
  55. do_something();
  56. }
  57.  
  58. ?>

URL: http://www.bytemycode.com/snippets/snippet/657/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.