cURL不发送POST数据,但在终端中正常工作

时间:2012-06-28 22:32:54

标签: php cordova curl

这是在命令行中运行的curl代码:

  $ curl -F file=@/path/to/index.html -u lslkdfmkls@gmail.com -F 'data={"title":"API V1  App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}' https://build.phonegap.com/api/v1/apps

这是我的代码:

$ch = curl_init();

$data = array("title"=>"sampele title","package"=>"com.fsdlfn.sdfknsdj","version"=>"0.1.0","create_method"=>"file","file"=>"@/path/myfolder/myfile.zip");

$jsdata = json_encode($data);

curl_setopt($ch, CURLOPT_URL, 'https://build.phonegap.com/api/v1/app?auth_token='.$token); //got this token already, so using that here .
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsdata);

echo curl_exec($ch);

curl命令在终端工作,但上面的curl命令用php编写,返回错误:

{"error":"no create_method specified: file, remote_repo, or hosted_repo"}

可以解决什么问题?

谢谢

1 个答案:

答案 0 :(得分:0)

试试这个:

$ch = curl_init();

$data = array("title"=>"sampele title","package"=>"com.fsdlfn.sdfknsdj","version"=>"0.1.0","create_method"=>"file");

$jsdata = json_encode($data);

curl_setopt($ch, CURLOPT_URL, 'https://build.phonegap.com/api/v1/app?auth_token='.$token); //got this token already, so using that here .
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $jsdata, 'file'=>'@/path/myfolder/myfile.zip'));

echo curl_exec($ch);

这就是我修复的原因:

  1. $data正在json_encode d,因此cURL将看不到file属性,它将作为字符串发送,而不是读取文件 - 这就是我放置的原因file直接在POSTFIELDS
  2. 变量$data不会将其作为data=...发送,而是将其作为单个字符串发送(例如POST XML)。