
wp remote post – wp_remote_post vs curl untuk mengirim data dalam plugin WordPress
Saya memiliki kode ikal ini dan berfungsi sebagaimana mestinya. Kode ini menghubungi server saya:
$curl = curl_init();
$post_data = array();
$post_data[] = "plugin: $plugin";
$post_data[] = "token: $token";
curl_setopt($curl, CURLOPT_HTTPHEADER, $post_data);
$post_data = array();
$post_data['code'] = $token;
$post_data['plugin'] = $plugin;
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_CAINFO,"...");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_URL, $url );
$response = curl_exec($curl);
if (curl_errno($curl)) {
return(curl_errno($curl));
} else{
return $response;
}
curl_close($curl);
Karena ini adalah bagian dari plugin WordPress, saya diberitahu akan lebih baik menggunakan wp_remote_post. Saya telah berhasil melakukan ini:
$response = wp_remote_post($url, array(
'method' => 'POST',
'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
'body' => array(
'token' => $token,
'plugin' => $plugin,
)
));
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
return $response['body'];
}
Ini saat ini berfungsi tetapi pertanyaan saya adalah bagaimana saya bisa menulis ini sehingga benar-benar menyerupai kode curl? Dalam kode ikal saya, saya memiliki beberapa bagian lain seperti VERIFYPEER, CAINFO dll..