Reputation: 209
I have a server that prompts for http authentication before it gives personalized json results.
How can I write a php script that runs on another box to prompt for the auth, pass it along and pull the results?
Upvotes: 0
Views: 199
Reputation: 764
make sure this is going with SSL. otherwise, anyone could hijack your unencrypted credential.
Upvotes: 1
Reputation: 1774
Just create a HTML form with login and password inputs, and then retrieve data with cURL.
$curl = curl_init('http://example.com/api');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, $_POST['login'].':'.$_POST['password']);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($curl);
If you want to be more "interactive" try to add some AJAX stuff.
Upvotes: 1
Reputation: 3867
Change USER:PASS to be the username and password, and change the URL to your URL. The return value is in $jsonStr.
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
// Puts return in variable rather than the browser
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "USER:PASS");
// grab URL and pass it to the variable
$jsonStr = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Upvotes: 0