[PHP] Is URL online?


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

Return true if URL is online.


Copy this code and paste it in your HTML
  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
  18. Host: $url[host]
  19.  
  20. "); //socket opened
  21. $headers = fread($fp, 4096);
  22. fclose($fp);
  23.  
  24. if(preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers)){
  25. //matching header
  26. return true;
  27. }
  28. else return false;
  29.  
  30. } // if parse url
  31. else return false;
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.