---
layout: page
title: "JavaScript get_headers function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/get_headers:415
- /functions/view/get_headers
- /functions/view/415
- /functions/get_headers:415
- /functions/415
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's get_headers

{% codeblock url/get_headers.js lang:js https://raw.github.com/kvz/phpjs/master/functions/url/get_headers.js raw on github %}
function get_headers (url, format) {
  // From: http://phpjs.org/functions
  // +   original by: Paulo Freitas
  // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
  // -    depends on: array_filter
  // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
  // %        note 1: Synchronous so may lock up browser, mainly here for study purposes.
  // *          test: skip
  // *     example 1: get_headers('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm')[0];
  // *     returns 1: 'Date: Wed, 13 May 2009 23:53:11 GMT'

  var req = this.window.ActiveXObject
    ? new ActiveXObject("Microsoft.XMLHTTP")
    : new XMLHttpRequest();

  if (!req) {
    throw new Error('XMLHttpRequest not supported');
  }
  var tmp, headers, pair, i, j = 0;
ß
  req.open('HEAD', url, false);
  req.send(null);

  if (req.readyState < 3) {
    return false;
  }

  tmp = req.getAllResponseHeaders();
  tmp = tmp.split('\n');
  tmp = this.array_filter(tmp, function (value) {
    return value.substring(1) !== '';
  });
  headers = format ? {} : [];

  for (var i in tmp) {
    if (format) {
      pair = tmp[i].split(':');
      headers[pair.splice(0, 1)] = pair.join(':').substring(1);
    } else {
      headers[j++] = tmp[i];
    }
  }

  return headers;
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/url/get_headers.js)

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are 
the closest match to this hashtable-like data structure. 

Please also note that php.js offers community built functions and goes by the 
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online 
functions that are far from perfect, in the hopes to spark better contributions. 
Do you have one? Then please just: 

 - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/url/get_headers.js)

### Example 1
This code
{% codeblock lang:js example %}
get_headers('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm')[0];
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
'Date: Wed, 13 May 2009 23:53:11 GMT'
{% endcodeblock %}


### Other PHP functions in the url extension
{% render_partial _includes/custom/url.html %}
