PHP + curl, HTTP POST sample code?

前端 未结 11 2351
北荒
北荒 2020-11-21 04:58

Can anyone show me how to do a php curl with an HTTP POST?

I want to send data like this:

username=user1, password=passuser1, gender=1
11条回答
  •  -上瘾入骨i
    2020-11-21 05:51

    Procedural

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

    Object oriented

    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;
        }
    }
    

    Usage

    // 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()));
    }
    

    Side note here: it would be best to create some kind of interface called AdapterInterface for example with getResponse() method and let the class above implement it. Then you can always swap this implementation with another adapter of your like, without any side effects to your application.

    Using HTTPS / encrypting traffic

    Usually there's a problem with cURL in PHP under the Windows operating system. While trying to connect to a https protected endpoint, you will get an error telling you that certificate verify failed.

    What most people do here is to tell the cURL library to simply ignore certificate errors and continue (curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);). As this will make your code work, you introduce huge security hole and enable malicious users to perform various attacks on your app like Man In The Middle attack or such.

    Never, ever do that. Instead, you simply need to modify your php.ini and tell PHP where your CA Certificate file is to let it verify certificates correctly:

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

    The latest cacert.pem can be downloaded from the Internet or extracted from your favorite browser. When changing any php.ini related settings remember to restart your webserver.

提交回复
热议问题