问题描述
限时送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:关键词]
发布评论