简体   繁体   English

php进程http认证

[英]php process http authentication

I have a server that prompts for http authentication before it gives personalized json results. 我有一个服务器,在提供个性化的json结果之前提示进行http身份验证。

How can I write a php script that runs on another box to prompt for the auth, pass it along and pull the results? 我如何编写一个在另一个框上运行的PHP脚本来提示auth,传递它并拉出结果?

Just create a HTML form with login and password inputs, and then retrieve data with cURL. 只需创建一个包含登录名和密码输入的HTML表单,然后使用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. 如果你想更加“互动”,试着添加一些AJAX的东西。

make sure this is going with SSL. 确保使用SSL。 otherwise, anyone could hijack your unencrypted credential. 否则,任何人都可能劫持您未加密的凭证。

Change USER:PASS to be the username and password, and change the URL to your URL. 更改USER:PASS为用户名和密码,并将URL更改为您的URL。 The return value is in $jsonStr. 返回值在$ 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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