Reputation: 1171
In LIBCURL for PHP what is the equivalent to a basic curl -d?
This is my basic CURL: I need to format it for LIBCURL in PHP:
curl -u username:password -H "Content-Type:application/json" -X POST -d '[{"phoneNumber":"12135551100","message":"Hello World!"}]' "https://api.example.com/v2/texts"
I have tried using CURLOPT_WRITEFUNCTION
and CURLOPT_WRITEDATA
but I can't seem to get my request to work.
Upvotes: 0
Views: 374
Reputation: 415
The option required is CURLOPT_POSTFIELDS. The specification is the same as the libcurl reference.
There are some PHP examples in the curl_setopt reference. The simplest way being the following example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "postvar1=value1&postvar2=value2");
Upvotes: 2
Reputation: 1171
My endpoint needed data in the form of an array so this worked.
function doPost($url, $user, $password, $params = array()) {
$authentication = 'Authorization: Basic '.base64_encode("$user:$password");
$http = curl_init($url);
curl_setopt($http, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($http, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($http, CURLOPT_RETURNTRANSFER, true);
curl_setopt($http, CURLOPT_URL, $url);
curl_setopt($http, CURLOPT_POST, true);
curl_setopt($http, CURLOPT_POSTFIELDS, $params);
curl_setopt($http, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', $authentication));
return curl_exec($http);
}
My array formatted like this:
$params = '[{"phoneNumber":"' . $ToNumber . '","message":"' . $msg . '"}]';
Upvotes: 0