PHP - 如何在安全URL(HTTPS)上触发HTTP get请求?

时间:2012-10-08 23:37:28

标签: php xml curl https http-get

我正在尝试在安全URL上发出HTTP GET请求,该URL要求输入用户名和密码。当我在浏览器中使用它时,这很好,但我不知道如何使用PHP。

我尝试过使用这两种方法:

1)按照此处的建议使用Curl:Make a HTTPS request through PHP and get response

2)使用这里建议的file_get_contents:How to send a GET request from PHP?

但是第一个没有给我任何回应。第二个给了我以下错误:

failed to open stream: HTTP request failed

这是我的卷曲代码:

$url="https://xxxxx.com";
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;

和file_get_contents:

$url="https://xxxx.com";
$response=file_get_contents($url);
echo $response;

该URL将返回我正在测试的API的XML响应。有人能指出我正确的方向吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

如果我们专注于发送用户名和密码的要求,因为我怀疑这是您的主要问题,请试试这个

$ch = curl_init();

$url="https://xxxxx.com";
// OR - check with your server's operator
$url="http://xxxxx.com";

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// or maybe 
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
// - see http://stackoverflow.com/questions/4753648/problems-with-username-or-pass-with-colon-when-setting-curlopt-userpwd
// check the cURL documentation

$output = curl_exec($ch);
$info = curl_getinfo($ch);
// don't forget to check the content of $info, even a print_r($info) is better 
// than nothing during debug
curl_close($ch);