Vinny Vinny - 1 year ago 173
PHP Question

Convert Terminal cURL to PHP cURL Script

I'm trying to post the following value into an API, and get back the response, it's working fine on terminal with curl command, but not on my PHP file running on localhost with MAMP.


Here's my PHP code that isn't working:

function doRequest($method, $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip', 'deflate');
curl_setopt($ch, CURLOPT_USERAGENT, "CarteiraPagamento/1.0.3 (iPhone; iOS 9.3.2; Scale/2.00)");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, getcwd().'/cookies/out.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, getcwd().'/cookies/out.txt');
curl_setopt($ch, CURLOPT_REFERER, '');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"userCode":"user478","imei":"39BB4E91-71E8-468D-9FDE-AA2222A93F04","deviceModel":"iPhone5,3","email":""}');

When I run the curl command on terminal, I get the right response.

curl -i -s -k -X 'POST' \
-H 'Content-Type: application/json; charset=utf-8' -H 'User-Agent: CarteiraPagamento/1.0.3 (iPhone; iOS 9.3.2; Scale/2.00)' \
--data-binary $'{\"userCode\":\"user478\",\"imei\":\"39BB4E91-71E8-468D-9FDE-AA2222A93F04\",\"deviceModel\":\"iPhone5,3\",\"email\":\"\"}' \

How can I convert this command to work with PHP curl?

Answer Source

It worked after adding this line to the cURL:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download