关于php:如何使用cURL发出HTTPS请求?

How to make an HTTPS request using cURL?

我有2个php脚本,用于发送xml文件并捕获它。我正在使用cURL,一切正常。现在,我尝试执行相同的操作,但是使用基于SSL的HTTP(HTTPS)。我已经使用XAMPP安装了本地服务器,并且按照以下信息设置了SSL:在本地xampp / apache服务器上设置SSL。

我试图像这样发送xml文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
  /*
   * XML Sender/Client.
   */

  // Get our XML. You can declare it here or even load a file.



  $xml = file_get_contents("data.xml");


  // We send XML via CURL using POST with a http header of text/xml.
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");

  //i use this line only for debugging through fiddler. Must delete after done with debugging.
  curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');

  // set URL and other appropriate options
  curl_setopt($ch, CURLOPT_URL,"https://ipv4.fiddler/iPM/receiver.php");
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
  curl_setopt($ch, CURLOPT_REFERER, 'https://ipv4.fiddler/iPM/receiver.php');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $ch_result = curl_exec($ch);
  echo"Result =".$ch_result;
  curl_close($ch);
  // Print CURL result.
?>

我从此处下载了cURL的新证书:

http://curl.haxx.se/ca/cacert.pem

我不确定应该将证书放在哪里,但是我将其放在该项目的工作区目录中。

现在的问题是XML文件从未发送到接收方。有什么想法吗?


您通过CURLOPT_CAINFO传递给cURL的cacert.pem用于验证证书颁发机构,但开发服务器通常具有不包含在该捆绑软件中的自签名证书。

第一步是生成自己的自签名证书。本文分步介绍了该过程。确保在CSR生成过程中,您使用的是Common Name (CN)下的预期服务器名称,例如ipv4.fiddler

使用自签名证书(例如server.crt)和密钥(例如server.key)配置了Web服务器之后,您需要将前者复制到脚本可以访问它的位置。

以下基本要素可用于验证整个内容:

1
2
3
4
5
6
7
8
9
10
11
12
$ch = curl_init('https://ipv4.fidler');
curl_setopt_array($ch, array(
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_VERBOSE => true,
    CURLOPT_CAINFO => '/path/to/server.crt',
));

if (false === curl_exec($ch)) {
    echo"Error while loading page:", curl_error($ch),"\
"
;
}


如果我要使用Curl发送ssl发布请求,而无需验证证书,则可以使用以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$data = array(
    'name' => $name,
    'ip' => $ip,
    'text'=>"text"
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,'https://myserver.com/index.php/');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
          http_build_query($data));

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);