简体   繁体   中英

POST Request PHP with Curl

I'm working on a wordpress project where I have to modify my theme, so I can request a JSON to an external API. I've been searching through the internet how to do that and a lot of people use CURL.

I must do a POST request, yet I don't know how it works or how to do it. So far I've got this code running:

 $url='api.example.com/v1/property/search/';

 $data_array =  array(

            $id_company     =>  '123456',
            $api_token     =>  'abcd_efgh_ijkl_mnop',
    );

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_POSTFIELDS, $data_array);
        curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'APIKEY: 111111111111111111111',
        'Content-Type: application/json'
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

        $result = curl_exec($curl);
        if(!$result){die("Connection Failure");}
        curl_close($curl);
         echo($result);

I don't know where exactly I should put my authentication info or how does the curl methods work in PHP. Can you guys check it out and help me solve this?

There are some answers out there that would help you, such as this one .

However, WordPress actually has built-in functions to make GET and POST requests (that actually fall back to cURL I believe?) named wp_remote_get() and wp_remote_post() . Clearly in your case, you'll want to make use of wp_remote_post() .

$url = 'https://api.example.com/v1/property/search/';

$data_array = array(
    'id_company' => 123456,
    'api_token'  => 'abcde_fgh'
);

$headers = array(
    'APIKEY' => 1111111111,
    'Content-Type' => 'application/json'
);

$response = wp_remote_post( $url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => $headers,
        'body' => $data_array,
        'cookies' => array()
    )
);

if( is_wp_error( $response ) ){
    $error_message = $response->get_error_message();
    echo "Something went wrong: $error_message";
} else {
    echo 'Success! Response:<pre>';
        print_r( $response );
    echo '</pre>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM