I’m attempting to implement a PHP method of authenticating a request to Associated Press feeds. From their docs:
To authenticate all feed and content requests, the AP WebFeeds system uses HTTP Basic Authentication, which is currently the standard for syndicated feeds. Most feed readers and reader components allow the configuration of user credentials ahead of time and pass them in the headers rather than in the URL.
Important: Passing the credentials directly in the URL is currently widely blocked. For more information, see Microsoft’s security bulletin at http://www.microsoft.com/technet/security/bulletin/MS04-004.mspx.
You can configure a reader or component to create an authentication header with the name / value in the following format:
("Authorization", "Basic " + {Encoded_username_and_password})where
{Encoded_username_and_password}is replaced with the Base64 encoding of the bytes in the string “username:password.”If you are writing your own client code to download a feed, use HTTP Basic Authentication that is built into your programming language’s library. HTTP Basic Authentication is available on most platforms; for example, Perl, PHP, C or Java.
My attempt is:
/**
* Begin Transaction
*/
$url = "http://syndication.ap.org/AP.Distro.Feed/GetFeed.aspx?idList=" . implode(',', $idList) . "&idListType=products&maxItems=25";
$auth = "Authorization=Basic " . base64_encode($user . ":" . $pass);
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_POST, 1); // set POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $auth); // add POST fields
$result = curl_exec($ch); // run the whole process
curl_close($ch);
/**
* End Transaction
*/
var_dump($result);
Which gives me:
string(405) "
Authentication
FeedServer
Authentication Failed on GetFeed
Authentication denied no auth credentials detected
"
What’s the correct way to authenticate this request in PHP?
Authorization is an HTTP header not a POST parameter. You used
CURLOPT_POSTFIELDSwhich sets the body of the request. Instead, you need to set it usingCURLOPT_HTTPHEADER(The entry for it is pretty far down in the list):And in case it wasn’t obvious already, you don’t need to make this as a post request (unless the API requires it), so you can remove: