I'm building a REST web service client in PHP and at the moment I'm using curl to make requests to the service.
How do I use curl to make authenticated (http basic) requests? Do I have to add the headers myself?
I'm building a REST web service client in PHP and at the moment I'm using curl to make requests to the service.
How do I use curl to make authenticated (http basic) requests? Do I have to add the headers myself?
I've solved the problem with putting the API key as 'x-api-key' in the HTTP Header.
This looks like the following code:
$api_key = 'abc';
$token = 'xyz';
$authorization = 'Authorization: Bearer ' . $token;
$api = 'x-api-key: ' . $api_key;
curl_setopt($curl, CURLOPT_HTTPHEADER, array($authorization, $api));
This is the only method that worked for me so far:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} ...
But I don't believe there isn't a better way.
require 'sinatra'
helpers do
def protected!
unless authorized?
response['WWW-Authenticate'] = %(Basic realm="Testing HTTP Auth")
throw(:halt, [401, "Not authorizedn"])
end
end
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
@auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['admin', 'admin']
end
end
before { protected! unless request.path_info == "/public" }
get('/public') { "I'm public!" }
There is a redirection - i use file_get_contents()
(but why not curl) and $http_response_header
:
$uid = 36377783;
$xUrl = "http://www.roblox.com/Asset/BodyColors.ashx?userId=".$uid;
$opts = array(
'http'=>array(
'method'=>"GET",
'follow_location' => true,
'header'=>
"Host: www.roblox.comrn" .
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0rn" .
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8rn" .
"Accept-Encoding: gzip, deflatern" .
"DNT: 1rn"
)
);
$context = stream_context_create($opts);
$xml = file_get_contents($xUrl, false, $context);
#print_r($http_response_header);
$url_redirect = str_replace('Location: ',"",$http_response_header[5]);
#print $url_redirect;
$xml = file_get_contents($url_redirect);
#print_r($xml);
$roblox_responses = new SimpleXMLElement($xml);
print_r($roblox_responses);
You want this:
Zend has a REST client and zend_http_client and I'm sure PEAR has some sort of wrapper. But its easy enough to do on your own.
So the entire request might look something like this: