3

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.

{"userCode":"user478","imei":"39BB4E91-71E8-468D-9FDE-AA2222A93F04","deviceModel":"iPhone5,3","email":"example@mail.com"}

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, 'https://example.com/');
    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":"example@mail.com"}');    
    }

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\":\"example@mail.com\"}' \
'https://ws.example.com/example'

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

Vinny
  • 597
  • 3
  • 11
  • 26

2 Answers2

0

Copy your terminal curl script and import it to Postman. Then convert it to PHP CURL from export options. No need to transform manually.

Ref -

  1. https://www.getpostman.com/docs/importing_curl
  2. How to export specific request to file using postman
Community
  • 1
  • 1
kawadhiya21
  • 2,458
  • 21
  • 34
  • 1
    I always get this error when I try to import the cURL. `Error while importing Curl: Zero or Multiple option-less arguments. Only one is supported (the URL)` – Vinny Jul 29 '16 at 04:05
0

It worked after adding this line to the cURL:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8'));
Vinny
  • 597
  • 3
  • 11
  • 26