用二进制数据构造一个 PHP POST 请求

编程入门 行业动态 更新时间:2024-10-13 02:18:18
本文介绍了用二进制数据构造一个 PHP POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试构建一个包含一些二进制数据的 PHP POST 请求,接下来是 之前的 StackOverflow 问题.数据正在提交给这个 API 调用:http://www.cyclestreets/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/api/#addphoto

这是我的 PHP 代码:

This is my PHP code:

$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/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 字段的键=>值对的原始数组.没有必要做所有 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 05:50:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/930420.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:二进制数   PHP   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!