【问题标题】:PHP - How to fire HTTP get request on a secured URL (HTTPS)?PHP - 如何在安全 URL (HTTPS) 上触发 HTTP 获取请求?
【发布时间】:2012-10-08 23:37:27
【问题描述】:

我正在尝试在要求用户名和密码的安全 URL 上触发 HTTP GET 请求。当我从浏览器中使用它时这很好,但我不确定如何使用 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

这是我的 curl 代码:

$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 响应。有人能指出我正确的方向吗?

谢谢!

【问题讨论】:

  • 您可能会混淆访问限制(例如基本身份验证和 co)和 https - 您确定服务器需要 https 吗?如果你需要基本身份验证,你必须告诉 curl 给网络服务器一个用户名和密码。

标签: php xml curl https http-get


【解决方案1】:

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

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

【讨论】:

  • 感谢 fvu 的快速响应。我已经尝试过您的代码,但仍然没有运气。 $info 只是打印出文本“Array”。
  • 是的,服务器需要 https。否则我会收到 404 错误。
  • @meraz 你确定你用过print_r 吗?因为它应该显示 FALSE(错误时)或帮助您诊断传输或问题的完整变量集。
  • 哎呀对不起我的错。我使用了 echo 而不是 print_r。好的,所以 print_r 看起来像这样:( [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.05831 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => 数组 () [redirect_url] => )
猜你喜欢
  • 2018-05-31
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 2011-05-19
  • 2012-05-22
  • 2016-04-26
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多