用二进制数据构造一个PHP POST请求 [英] Construct a PHP POST request with binary data

查看:263
本文介绍了用二进制数据构造一个PHP POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构造一个PHP POST请求,该请求包含一些二进制数据,随后是 http://www.cyclestreets.net/api/#添加照片

I'm trying to construct a PHP POST request that includes some binary data, following on from a previous StackOverflow question. The data is being submitted to this API call: http://www.cyclestreets.net/api/#addphoto

这是我的PHP代码:

$file = $_FILES['mediaupload'];
$file_field="@$file[tmp_name]";
$fields = array(
    'mediaupload'=>$file_field,
    'username'=>urlencode($_POST["username"]),
    'password'=>urlencode($_POST["password"]),
    'latitude'=>urlencode($_POST["latitude"]),
    'longitude'=>urlencode($_POST["longitude"]),
    'datetime'=>urlencode($_POST["datetime"]),
    'category'=>urlencode($_POST["category"]),
    'metacategory'=>urlencode($_POST["metacategory"]),
    'caption'=>urlencode($_POST["description"])
);
$fields_string = http_build_query($fields);
echo 'FIELDS STRING: ' . $fields_string;
$url = 'https://www.cyclestreets.net/api/addphoto.json?key=$key';
$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_RETURNTRANSFER, 1);
$response = curl_exec ($ch);

这是我的PHP文件输出:

This is what my PHP file outputs:

FIELDS STRING: mediaupload=%40%2Fprivate%2Fvar%2Ftmp%2FphpHjfkRP&username=testing&password=testing&latitude=auto&longitude=auto&datetime=auto&category=cycleparking&metacategory=good&caption=
API RESPONSE: {"request":{"datetime":"1309886656"},"error":{"code":"unknown","message":"The photo was received successfully, but an error occurred while processing it."},"result":{}}

我相信这意味着除了二进制数据的格式之外,关于请求的其他所有内容都可以.谁能告诉我我做错了什么?

I believe this means that everything else about the request is OK, apart from the format of the binary data. Can anyone tell me what I am doing wrong?

推荐答案

CURL可以接受POST字段的key => value对的原始数组.不需要做所有urlencode()和http_build_query()事情.数组中的@很可能被整顿为%40,因此CURL不会将其视为文件上载尝试.

CURL can accept a raw array of key=>value pairs for POST fields. There's no need to do all that urlencode() and http_build_query() stuff. Most likely the @ in the array is being mangled into %40, so CURL doesn't see it as a file upload attempt.

$fields = array(
    'mediaupload'=>$file_field,
    'username'=> $_POST["username"),
    etc...

curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);

这篇关于用二进制数据构造一个PHP POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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