2

So, I'm having a problem retrieving custom headers from ajax call.

This is my ajax call:

$.ajax({
    url: 'api.php',
    type: 'get',
    processData: false,
    beforeSend: function(xhr) {
        xhr.setRequestHeader('HASH', '5c268592cd4db9c7f6b813bb689005c6');
    },
    success: function(data) {
        console.log(data);
    },
    error: function(xhr, status, error) {
        console.log(xhr);
    }
});

And in my api.php, I have this:

<?php
    $headers = getallheaders();
    print_r(json_encode($headers));

the output:

......
"Access-Control-Request-Headers":"content-type,hash",
....

This returns null:

echo $headers['hash'];
// or this echo $headers['HASH'];
shaNnex
  • 1,043
  • 2
  • 19
  • 34

2 Answers2

0

You are making a cross-origin request (you shouldn't be, since your code shows a relative URL, but perhaps there is an HTTP redirect in play somewhere) and adding custom headers.

This means that it is not a simple request, but requires a preflight OPTIONS request.

The output you see is the headers of the OPTIONS request asking permission from the server to send the request with the custom headers.

You need to grant that permission, then the browser will make a second request (which is the one you are expecting).

header("Access-Control-Allow-Origin: http://example.com/");
header("Access-Control-Allow-Headers: HASH, Content-Type");
header("Access-Control-Allow-Methods: GET");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

Try this $_SERVER["HTTP_HASH"];