将终端cURL转换为PHP cURL脚本 [英] Convert Terminal cURL to PHP cURL Script

查看:126
本文介绍了将终端cURL转换为PHP cURL脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下值发布到API中,并获取响应,它在使用curl命令的终端上运行正常,但是在运行MAMP的本地主机上的PHP文件上却无法正常工作。

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"}

这是我的PHP代码, t工作:

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

在终端上运行curl命令时,得到正确的响应。 / p>

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'

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

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

推荐答案

在将以下行添加到cURL之后,它就起作用了:

It worked after adding this line to the cURL:

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

这篇关于将终端cURL转换为PHP cURL脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆