Posted By

goo on 01/05/13


Tagged

Online


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

clacwebstudio
maxid


[PHP] Is URL online?


 / Published in: PHP
 

Return true if URL is online.

  1. function is_online( $url ){
  2. $url = @parse_url($url);
  3. if (!$url) return false;
  4.  
  5. $url = array_map('trim', $url);
  6. $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
  7.  
  8. $path = (isset($url['path'])) ? $url['path'] : '/';
  9. $path .= (isset($url['query'])) ? "?$url[query]" : '';
  10.  
  11. if (isset($url['host']) && $url['host'] != gethostbyname($url['host'])) {
  12.  
  13. $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
  14.  
  15. if (!$fp) return false; //socket not opened
  16.  
  17. fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n"); //socket opened
  18. $headers = fread($fp, 4096);
  19. fclose($fp);
  20.  
  21. if(preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers)){
  22. //matching header
  23. return true;
  24. }
  25. else return false;
  26.  
  27. } // if parse url
  28. else return false;
  29. }

Report this snippet  

You need to login to post a comment.