Use PHP functions in JavaScript

JavaScript get_headers

fetches all the headers sent by the server in response to a HTTP request

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
function get_headers (url, format) {
    // +   original by: Paulo Freitas
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        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.    // *     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 (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;
}
external links: original PHP docs | raw js source

Examples

Running

1
get_headers('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm')[0];

Should return

1
'Date: Wed, 13 May 2009 23:53:11 GMT'

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have get_headers goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
T.Wild
Jan 27th Permalink

q  This should be marked as having a dependency on array_filter (line 23) or be recoded.

Gravatar
Brett Zamir
22 Nov '10 Permalink

q  @Joey: Due to security restrictions in JavaScript, this function can only work if the script you are trying to get is on the same domain (or if the site you are targeting is granting HTML5 CORS access and browsers support it).

Gravatar
Joey
21 Nov '10 Permalink

q  I have a problem whit the http header the page give 303 see other, but i need the headers of tha page! But the function don't show how to fix.

Gravatar
Kevin van Zonneveld
10 Dec '08 Permalink

q  @ Paulo Ricardo F. Santos: hehe, no problem! Thanks for giving the final function complete though, makes my job a little easier :)

Gravatar
Paulo Ricardo F. Santos
4 Dec '08 Permalink

q  OMG! Sorry for the flood and ignore my last 2 comments (#7 and #8 - I was quite confused). Here's the function with corrections:

[code=&quot;javascript&quot;]
function get_headers(url, format) {
var req = window.ActiveXObject ? new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;) : new XMLHttpRequest();
if (!req) throw new Error('XMLHttpRequest not supported');
var tmp, headers, pair, i;

req.open('HEAD', url, false);
req.send(null);

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

tmp = req.getAllResponseHeaders();alert(tmp);
tmp = tmp.split('\n');
tmp = array_filter(tmp, function (value) { return value.substring(1) != ''; });
headers = [req.status + ' ' + req.statusText];

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

return headers;
}
[/code]
About the Opera problem, I don't know how to fix it. In my tests, Opera 9.62 returned a empty string in statusText property and getAllResponseHeaders() function - only status property returned as expected. Both Firefox 3 and IE 7 worked perfectly. :)

Gravatar
Paulo Ricardo F. Santos
4 Dec '08 Permalink

q  Ah! This line:

headers[pair.splice(0, 1)] = pair.join(':').replace(/^\s+|\s+$/g, '');



might be only this, there's no difference:

headers[pair.splice(0, 1)] = pair.join(':');



And as far I've noted, to work properly in Opera, the AJAX request should be asynchronized, as here: http://www.ceciliadassi.com/get_headers2.js. Synchronized requests returns false in the most of times. ;/

Gravatar
Paulo Ricardo F. Santos
4 Dec '08 Permalink

q  Hmm, might be useful replace

[code=&quot;javascript&quot;]tmp.pop();[/code]

to

[code=&quot;javascript&quot;]tmp = array_filter(tmp, function (str) { return str.replace(/^\s+|\s+$/g, '') != ''; });[/code]

to avoid any unexpected problem. ;)

Gravatar
Paulo Ricardo F. Santos
4 Dec '08 Permalink

q  Oops, sorry for the inconvenient - it's a bit buggy and I don't know how it worked before.

This snippet should fixes all the problems:

[code=&quot;javascript&quot;] tmp = req.getAllResponseHeaders().split('\n');
tmp.pop();
headers = [req.status + ' ' + req.statusText];

for (i in tmp) {
if (format) {
pair = tmp[i].split(':');
headers[pair.splice(0, 1)] = pair.join(':').replace(/^\s+|\s+$/g, '');
} else {
headers[headers.length] = tmp[i];
}
}[/code]

Here's a temporary demo - working as expected: http://www.ceciliadassi.com/get_headers.html

[]'s

Gravatar
Kevin van Zonneveld
3 Dec '08 Permalink

q  @ Paulo Ricardo F. Santos: I'm testing from console using the ./phpjstest.php file in the _tools directory in svn. But what's strange is that code from file_size (which I thought was identical) does not break.

Gravatar
Paulo Ricardo F. Santos
3 Dec '08 Permalink

q  @ Kevin: Ah! Well... how you are testing? AFAIK, there's no way to test it locally or request a cross-domain address. I've tested it on my test domain, requesting a file from same server. ;)

Gravatar
Kevin van Zonneveld
3 Dec '08 Permalink

q  @ Paulo Ricardo F. Santos: Well I haven't got it working yet, so that's why the examples are still in a copy-pasted state.

Gravatar
Paulo Ricardo F. Santos
3 Dec '08 Permalink

q  @ Kevin: Hmm, great idea, I forgot this possible abnormal behavior! &gt;.&lt;

Ah!, man, I don't understood your example. Why it should returns 123? o.O

Gravatar
Kevin van Zonneveld
3 Dec '08 Permalink

q  @ Paulo Ricardo F. Santos: In my test suite: phpjstest.php, readyState would stay at 1, I had to build a condition &lt; 3 to avoid the function from crashing. Very strange, because the file_exists function uses the same code and that works ok.


Contribute a New function

More functions

In this category

base64_decode
base64_encode
» get_headers
get_meta_tags
http_build_query
parse_url
rawurldecode
rawurlencode
urldecode
urlencode

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: AYHAN BARI*, Nikita Ekshiyan, Nikita Ekshiyan, Petr Pavel, @HalfWinter, Paulo Freitas, Andros Peña Romo, @andorosu, Raimund Szabo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !