如何使用PHP发送HTTPS帖子

Nic*_*rns 18 php https

我正在设置自定义电子商务解决方案,我正在使用的支付系统要求我发送HTTPS POSTS.

我怎么能用php(和CURL?)这样做,它与发送http帖子有什么不同?

更新:

感谢您的回复,他们非常有用.我假设我需要购买一个SSL证书才能使用,我显然会为最终网站做这个,但有没有办法让我在不购买的情况下进行测试?

谢谢,尼科

小智 40

PHP/Curl将处理https请求就好了.您可能需要做的事情,特别是在针对开发服务器时,关闭CURLOPT_SSL_VERIFYPEER.这是因为开发服务器可能是自签名的,并且验证测试失败.

$postfields = array('field1'=>'value1', 'field2'=>'value2');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://foo.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
// Edit: prior variable $postFields should be $postfields;
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
$result = curl_exec($ch);
Run Code Online (Sandbox Code Playgroud)

  • @VivekSancheti 可能需要启用 SSL 验证,并创建证书 PEM 文件 (2认同)

Vol*_*erK 12

您还可以使用流api和http/https上下文选项

$postdata = http_build_query(
  array(
    'FieldX' => '1234',
    'FieldY' => 'yaddayadda'
  )
);

$opts = array(
  'http' => array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded',
    'content' => $postdata
  )
);
$context  = stream_context_create($opts);
$result = file_get_contents('https://example.com', false, $context);
Run Code Online (Sandbox Code Playgroud)

您仍然需要一个提供SSL加密的扩展.这可以是php_openssl或(如果以这种方式编译)php_curl.