Comprobar si existe un URL y esta Online – PHP
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:
[php]
$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;
[/php]
Tiempo: 0,222 segundos, nunca más de 0.225s
Curl:
[php]
$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;
[/php]
Tiempo: 0,224 segundos, pocas veces llegó a 0,227
Headers:
[php]
@$headers = get_headers($url);
if (preg_match(‘/^HTTP\/\d\.\d\s+(200|301|302)/’, $headers[0])){
return true;
}
else return false;
[/php]
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:
[php]
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;
}
[/php]