问题
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.
CURLOPT_SAFE_UPLOAD
option disables support for the@
prefix for uploading files inCURLOPT_POSTFIELDS
which is exactly what you need to use.CURLOPT_POST
option expects a boolean value (true
orfalse
), althoughcount($fields)
in your case will be evaluated totrue
anyway.-F
option in the source curl command forcesContent-Type
value tomultipart/form-data
. This mean that in PHP you have to pass data toCURLOPT_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