Inicio > Programación Web > Comprobar si existe un URL y esta Online – PHP

Comprobar si existe un URL y esta Online – PHP

jueves, 25 de enero de 2024 Dejar un comentario Ir a comentarios

Imagina que necesitas comprobar si un sitio esta en linea o no, parece bastante fácil, ya que hay un montón de herramientas para realizar esto, pero esto puede ser un cuello de botella para tu aplicación.

Lo he intentado diferente maneras utilizando sockets, encabezados y curl con el fin de conocer cual es la opción mas rápida.

Probé el código con el sitio yahoo.com (10 intentos cada uno y conseguimos el mejor resultado de tiempo):


Sockets + Header:

$url = @parse_url($url);
if (!$url) return false;

$url = array_map('trim', $url);
$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];

$path = (isset($url['path'])) ? $url['path'] : '/';
$path .= (isset($url['query'])) ? "?$url[query]" : '';

if (isset($url['host']) && $url['host'] != gethostbyname($url['host'])) {

     $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

      if (!$fp) return false; //socket not opened

        fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n"); //socket opened
        $headers = fread($fp, 4096);
        fclose($fp);

	 if(preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers)){//matching header
	       return true;
	 }
	 else return false;

 } // if parse url
 else return false;

Tiempo: 0,222 segundos, nunca más de 0.225s

Curl:

$resURL = curl_init();
curl_setopt($resURL, CURLOPT_URL, $url);
curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback');
curl_setopt($resURL, CURLOPT_FAILONERROR, 1);
curl_exec ($resURL);
$intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE);
curl_close ($resURL);
if ($intReturnCode != 200 && $intReturnCode != 302 && $intReturnCode != 304) {
    return false;
}
else return true;

Tiempo: 0,224 segundos, pocas veces llegó a 0,227

Headers:

@$headers = get_headers($url);
if (preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0])){
   return true;
}
else return false;

Tiempo: 0,891 segundos, pocas veces más de 1,5 »

Como se puede apreciar, para mí la forma más rápida es Socket + Encabezado, a pesar de que curl es bastante rápido!

También tenga en cuenta, que no hice uso de otros sistemas tales como fopen o file_get_contents ya que no es necesario recuperar la página, y lo que necesitamos es solo el encabezado.

Algo extra, para verificar una url:

function isURL($url){
	$pattern='|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i';
	if(preg_match($pattern, $url) > 0) return true;
	else return false;
}

Comparte y diviertete:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • BarraPunto
  • Bitacoras.com
  • BlinkList
  • Blogosphere
  • Live
  • Meneame
  • MSN Reporter
  • MySpace
  • RSS
  • Suggest to Techmeme via Twitter
  • Technorati
  • LinkedIn
  • email
  • FriendFeed
  • PDF
  • Reddit
  • Wikio IT
  • Add to favorites
  • blogmarks
Categories: Programación Web Tags: , , ,
Top Footer