Writing the following curl in PHP

耗尽温柔 提交于 2019-12-12 21:25:14

问题


How would I write the following Curl in PHP?

I need to automate this process in php.

$ curl -F file=@/Users/alunny/index.html -u andrew.lunny@nitobi.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

Here is the link to the Phonegap Build API.

http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_apps

Any help would be greatly appreciated.

This is what I have tried so far...

<?php

$url = 'https://build.phonegap.com/api/v1/apps';
$file = 'mobilecontainer.zip';

$fields = array(
    'title' => 'Test App',
    'create_method' => 'file',
    'private' => 'false'
);

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_SAFE_UPLOAD, 'true');

$result = curl_exec($ch);

print_r($result);

curl_close($ch);

回答1:


You use CURL options improperly.

  1. CURLOPT_SAFE_UPLOAD option disables support for the @ prefix for uploading files in CURLOPT_POSTFIELDS which is exactly what you need to use.
  2. CURLOPT_POST option expects a boolean value (true or false), although count($fields) in your case will be evaluated to true anyway.
  3. -F option in the source curl command forces Content-Type value to multipart/form-data. This mean that in PHP you have to pass data to CURLOPT_POSTFIELDS as array. This array should contain two elements: 'data' - json-encoded data, and 'file' - link to file to upload.

So the code should look like this:

$url = 'https://build.phonegap.com/api/v1/apps';
$data = array(
    'title' => 'Test App',
    'package' => 'com.alunny.apiv1',
    'create_method' => 'file',
    'version' => '0.1.0',
);
$post = array(
    'data' => json_encode($data),
    'file' => '@mobilecontainer.zip',
);

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);
curl_close($ch);

print_r($result);


来源:https://stackoverflow.com/questions/25180366/writing-the-following-curl-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!