PHP + curl, HTTP POST sample code?

前端 未结 11 2369
北荒
北荒 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:46

    Curl Post + Error Handling + Set Headers [thanks to @mantas-d]:

    function curlPost($url, $data=NULL, $headers = NULL) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        if(!empty($data)){
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
    
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
    
        $response = curl_exec($ch);
    
        if (curl_error($ch)) {
            trigger_error('Curl Error:' . curl_error($ch));
        }
    
        curl_close($ch);
        return $response;
    }
    
    
    curlPost('google.com', [
        'username' => 'admin',
        'password' => '12345',
    ]);
    

提交回复
热议问题