问题描述:

I have basic authentication enabled on an Apache server. The server is hosting an API that I implemented and I want to do is call this API from my PHP script. I got as far as figuring out how to create a header:

$user = 'my_name_api';

$pwd = 'xxxxxxxxx';

$auth_string = $user . ':' . $pwd;

$auth_b64 = base64_encode($auth_string);

$header = 'Authorization: Basic ' . $auth_b64;

How do I include the $header in my API calls? I am looking for something other than cURL, and I am NOT using any environments like zend, etc. (saw some example for Zend, etc., but I am not using any of those).

网友答案:

Have you tried fopen / file_get_contents?

Start here: http://php.net/manual/en/function.fopen.php

or here: http://www.php.net/manual/en/function.file-get-contents.php

and let me know how it goes...

airyt

网友答案:

If you don't need SSL or proxy support, you can use file_get_contents() with a stream context. The stream context can contain HTTP headers:

$opts = array
(
  'http'=>array
  (
    'method' => "GET",
    'header' => "Authorization: ..."
  )
);
$context = stream_context_create($opts);
$file = file_get_contents('http://www.example.com', false, $context);

More on this here.

相关阅读:
Top