I am trying to connect twilio api using Curl php. The following is the code from Twilio api
I used an online tool php to curl but it didn't converted the code with data encode url.
The question which was marked as duplicate has no information about --data-urlencode. I have tried the solution mentioned there but still it is not working the way it is suppose to.
curl -X POST https://api.twilio.com/2010-04-01/Accounts/ACCOUNTID/Messages.json \
--data-urlencode "From=+122344444" \
--data-urlencode "Body=Body" \
--data-urlencode "To=+13101111111" \
-u ACCOUNTID:PASSWORD
PHP Code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'ACCOUNTID' . ':' . 'PASSWORD');
The expected result is to get message but I am getting
{"code": 21603, "message": "A 'From' phone number is required.", "more_info": "https://www.twilio.com/docs/errors/21603", "status": 400}
The reason I am getting this is I am not sure how to pass from, body and to in curl php.
Percent-encoding, also known as URL encoding, is technically a mechanism for encoding data so that it can appear in URLs. This encoding is typically used when sending POSTs with the application/x-www-form-urlencoded content type, such as the ones curl sends with --data and --data-binary etc.
cURL can also encode the query with the --data-urlencode parameter. When using the --data-urlencode parameter the default method is POST so the -G parameter is needed to set the request method to GET.
PHP cURL GET request In the example, we send a GET request to a small website. The output is directly shown in the standard output. $ch = curl_init('http://webcode.me'); The curl_init function initializes a new session and returns a cURL handle for use with the curl_setopt , curl_exec , and curl_close functions.
cURL is a PHP library and command-line tool (similar to wget) that allows you to send and receive files over HTTP and FTP. You can use proxies, pass data over SSL connections, set cookies, and even get files that are protected by a login.
What you're missing is
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
where $payload
is
$payload = [
'From' => '+122344444',
'To' => '+13101111111',
'Body' => 'This is the body...'
];
$payload = [
'From' => '+122344444',
'To' => '+13101111111',
'Body' => 'This is the body...'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'ACCOUNTID' . ':' . 'PASSWORD');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With