Tag: encabezados - Webeame Snippets


Añadir snippet

Tag: encabezados



Obtener encabezados de una dirección web

Devuelve las cabeceras de una dirección web
  1. /**
  2. * function getHeaders (string $url, boolean $formato = true)
  3. *
  4. * Devuelve las cabeceras de una dirección web
  5. * Solo acepta HTTP como metodo
  6. *
  7. * Si $formato es true devuelve un array asociativo,
  8. * de lo contrario, un array de claves simples
  9. *
  10. * return array
  11. */
  12. function getHeaders ($url, $formato = true) {
  13. if (function_exists('get_headers')) {
  14. return @get_headers($url, $formato);
  15. }
  16.  
  17. $partes = @parse_url($url);
  18.  
  19. if (empty($partes['host'])) {
  20. return false;
  21. }
  22.  
  23. if (empty($partes['path'])) {
  24. $path = '/';
  25. } else {
  26. $path = $partes['path'];
  27. }
  28.  
  29. if (!empty($partes['query'])) {
  30. $path .= '?'.$partes['query'];
  31. }
  32.  
  33. $partes['port'] = isset($partes['port'])?$partes['port']:80;
  34.  
  35. $socket = fsockopen($partes['host'], $partes['port'], $errno, $errstr, 30);
  36.  
  37. if (!$socket) {
  38. return false;
  39. }
  40.  
  41. $header = 'HEAD '.$path.' HTTP/1.1'."\r\n"
  42. .'Host: '.$partes['host'].(empty($partes['port'])?'':(':'.$partes['port']))."\r\n"
  43. .'Connection: Close'."\r\n\r\n";
  44.  
  45. fwrite($socket, $header);
  46.  
  47. $datos = array();
  48. $fin = false;
  49.  
  50. while (!feof($socket) or ($fin == true)) {
  51. if ($header = fgets($socket, 1024)) {
  52. if ($header == "\r\n") {
  53. $fin = true;
  54. break;
  55. } else {
  56. $header = trim($header);
  57. }
  58.  
  59. if ($formato == 1) {
  60. $key = explode(':', $header);
  61. $key = array_shift($key);
  62.  
  63. if ($key == $header) {
  64. $datos[] = $header;
  65. } else {
  66. $datos[$key] = substr($header,strlen($key)+2);
  67. }
  68.  
  69. unset($key);
  70. } else {
  71. $datos[] = $header;
  72. }
  73. }
  74. }
  75.  
  76. fclose($socket);
  77.  
  78. return $datos;
  79. }

En PHP encabezados cabeceras url por Lito hace on 4/2/08 | Comentarios