PHP、cURL 和 HTTP POST 示例?

2022-08-30 05:49:18

任何人都可以向我展示如何使用HTTP POST进行PHP cURL?

我想像这样发送数据:

username=user1, password=passuser1, gender=1

www.example.com

我希望 cURL 返回类似 .有什么例子吗?result=OK


答案 1
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "postvar1=value1&postvar2=value2&postvar3=value3");

// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS, 
//          http_build_query(array('postvar1' => 'value1')));

// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close ($ch);

// Further processing ...
if ($server_output == "OK") { ... } else { ... }
?>

答案 2

程序

// set post fields
$post = [
    'username' => 'user1',
    'password' => 'passuser1',
    'gender'   => 1,
];

$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

// execute!
$response = curl_exec($ch);

// close the connection, release resources used
curl_close($ch);

// do anything you want with your response
var_dump($response);

面向对象

<?php

// mutatis mutandis
namespace MyApp\Http;

class CurlPost
{
    private $url;
    private $options;
           
    /**
     * @param string $url     Request URL
     * @param array  $options cURL options
     */
    public function __construct($url, array $options = [])
    {
        $this->url = $url;
        $this->options = $options;
    }

    /**
     * Get the response
     * @return string
     * @throws \RuntimeException On cURL error
     */
    public function __invoke(array $post)
    {
        $ch = \curl_init($this->url);
        
        foreach ($this->options as $key => $val) {
            \curl_setopt($ch, $key, $val);
        }

        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $post);

        $response = \curl_exec($ch);
        $error    = \curl_error($ch);
        $errno    = \curl_errno($ch);
        
        if (\is_resource($ch)) {
            \curl_close($ch);
        }

        if (0 !== $errno) {
            throw new \RuntimeException($error, $errno);
        }
        
        return $response;
    }
}

用法

// create curl object
$curl = new \MyApp\Http\CurlPost('http://www.example.com');

try {
    // execute the request
    echo $curl([
        'username' => 'user1',
        'password' => 'passuser1',
        'gender'   => 1,
    ]);
} catch (\RuntimeException $ex) {
    // catch errors
    die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode()));
}

这里的旁注:最好创建某种接口,例如使用方法调用,并让上面的类实现它。然后,您始终可以将此实现与您喜欢的另一个适配器交换,而不会对您的应用程序产生任何副作用。AdapterInterfacegetResponse()

使用HTTPS/加密流量

通常,在Windows操作系统下的PHP中的cURL存在问题。尝试连接到受 https 保护的终结点时,将收到一条错误消息,告诉您 .certificate verify failed

大多数人在这里所做的是告诉cURL库简单地忽略证书错误并继续()。由于这将使您的代码正常工作,因此您将引入巨大的安全漏洞,并使恶意用户能够对您的应用程序执行各种攻击,例如中间人攻击等。curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

永远不要这样做。相反,您只需要修改您的文件并告诉PHP您的文件在哪里,让它正确验证证书:php.iniCA Certificate

; modify the absolute path to the cacert.pem file
curl.cainfo=c:\php\cacert.pem

最新的可以从互联网上下载或从您喜欢的浏览器中提取。更改任何相关设置时,请记住重新启动Web服务器。cacert.pemphp.ini


推荐