PHP + curl, HTTP POST sample code?

前端 未结 11 2352
北荒
北荒 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 05:50

    curlPost('google.com', [
        'username' => 'admin',
        'password' => '12345',
    ]);
    
    
    function curlPost($url, $data) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($error !== '') {
            throw new \Exception($error);
        }
    
        return $response;
    }
    

提交回复
热议问题