【问题标题】:Writing the following curl in PHP用 PHP 编写以下 curl
【发布时间】:2014-08-07 10:39:14
【问题描述】:

我将如何在 PHP 中编写以下 Curl?

我需要在 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

这里是 Phonegap Build API 的链接。

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

任何帮助将不胜感激。

这是我迄今为止尝试过的......

<?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);

【问题讨论】:

  • 我已经更新了帖子。

标签: php curl phonegap-build


【解决方案1】:

您不正确地使用 CURL 选项。

  1. CURLOPT_SAFE_UPLOAD 选项禁用对 @ 前缀的支持 在CURLOPT_POSTFIELDS 上传文件,这正是你 需要使用。
  2. CURLOPT_POST 选项需要一个布尔值(truefalse), 尽管在您的情况下count($fields) 将被评估为true 无论如何。
  3. 源 curl 命令中的 -F 选项强制 Content-Type 值 到multipart/form-data。这意味着在 PHP 中你必须通过 数据到CURLOPT_POSTFIELDS 作为数组。这个数组应该包含两个 元素:'data' - json 编码数据,'file' - 文件链接 上传。

所以代码应该是这样的:

$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);

【讨论】:

  • 谢谢你,如何添加用户名,如果它要求你输入密码,你将如何用 curl 填写?
  • 在源 curl 命令中,-u 选项使用服务器身份验证。在 PHP 中,它的对应项是 CURLOPT_USERPWD 选项。它需要[username]:[password] 格式的字符串。
猜你喜欢
  • 2016-08-19
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
相关资源
最近更新 更多