James Wayne James Wayne - 2 months ago 8
PHP Question

How to attach authorization header via PHP?

I am using PHP to get JSON from a remote server via

file_get_contents
command. Here is the piece of code I used:

$opts = array(
'https'=>array(
'method'=>'GET',
'header'=>'Accept-language: en\r\n' .
'Authorization: MAC ["3","ios2.5.0","123","123abc","123=","abc="]\r\n' .
'User-Agent: abc/1.1.1 iOS/10.0.2 iPhone/iPhone7,1\r\n'
)
);

$context = stream_context_create($opts);

$file = file_get_contents('https://www.google.com/v11/file?search=ios&with=users%2Cfiles%2Cquestions', false, $context);

echo $file;


I did a quick debugging:


  1. Using Postman I was able to get the json file with the same header.

  2. I tried a different json from a different url, it works.

  3. I tried a local file, it works.


Answer

You have to understand what file_get_contents is. This command is a request to get the file on the server, in this case it is requesting to get https://www.google.com/v11/file/index.html on the server as in one single step. Since your url seems to use header to verify your origin, it might be an ajax request, meaning the server components didn't set up to allow an output from file_get_contents requests, instead they probably accept cURL requests.

So you can use:

curl_exec()
Comments