以下内容将使用cURL发送数据以及使用content-type application/x-www-form-urlencoded
发送的文件。
我不希望使用Content-Type: application/x-www-form-urlencoded
,而是使用Content-Type: application/json
。
我可以使用Content-Type: application/json
成功地仅发送数据。
如何使用Content-Type: application/json
发送数据和文件?
以下代码仅x-www-form-urlencoded,仅供参考
<?php
//Given:
$method='post';
$url='http://php.net/manual/en/function.curl-setopt.php';
$data=['hello'=>123];
$files=["image"=>["name" => "picture.jpg","type" => "image/jpeg","tmp_name" => "/path/on/server/to/tmp/phprj5rkG","error" => 0,"size" => 174476]];
//For using content-type application/x-www-form-urlencoded
$postData = [];
if($files) {
//cURL doesn't work out of the box with both files and POST data.
foreach ($files as $name=>$file){
$postData[$name] = new \CURLFile($file['tmp_name'],$file['type'],$file['name']);
}
if($data) {
foreach (explode('&', http_build_query($data)) as $pair){
list($name, $value) = explode('=', $pair, 2);
$postData[urldecode($name)] = urldecode($value);
}
}
}
else {
$postData=http_build_query($data);
}
$options=[
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referrer on redirect
];
switch ($method) {
case "get":
if ($postData) {$url = sprintf("%s?%s", $url, $postData);}
break;
case "post":
$options[CURLOPT_POST]=1;
$options[CURLOPT_POSTFIELDS]=$postData?$postData:'';
break;
case "put":
$options[CURLOPT_CUSTOMREQUEST]="PUT";
if ($postData) {$options[CURLOPT_POSTFIELDS]=$postData;}
break;
case "delete":
$options[CURLOPT_CUSTOMREQUEST]="DELETE";
if ($postData) {$options[CURLOPT_POSTFIELDS]=$postData;}
break;
}
$options[CURLOPT_URL]=$url;
$ch = curl_init();
curl_setopt_array( $ch, $options );
$rsp=curl_exec( $ch );