将终端cURL转换为PHP cURL脚本

时间:2016-07-11 03:21:05

标签: php curl

我试图将以下值发布到API中,然后返回响应,它在使用curl命令的终端上正常工作,但在使用MAMP的localhost上运行的PHP文件上没有。< / p>

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

这是我的PHP代码,它不起作用:

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"}');    
    }

当我在终端上运行curl命令时,我得到了正确的响应。

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'

如何将此命令转换为使用PHP curl?

2 个答案:

答案 0 :(得分:0)

复制终端卷曲脚本并将其导入Postman。然后从导出选项将其转换为PHP CURL。无需手动转换。

参考 -

  1. https://www.getpostman.com/docs/importing_curl
  2. How to export specific request to file using postman

答案 1 :(得分:0)

将此行添加到cURL后它起作用了:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8'));