简体   繁体   中英

php process http authentication

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?

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.

make sure this is going with SSL. otherwise, anyone could hijack your unencrypted credential.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM