使用curl将文件上传到远程api

时间:2017-08-17 04:41:55

标签: php curl file-upload

我正在尝试使用curl将用户上传的文件以及其他帖子数据上传到远程api。这就是我到目前为止所做的事情

$_POST['certf'] = '@'.$_FILES['certf']['tmp_name'].';filename=' . $_FILES['certf']['name'];

$url = "example.com/app_handler.php?key=key";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, "Content-Type:multipart/form-data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

在接收方我刚刚打印了$ _FILES,但它是空的。我在互联网上找到的所有教程都说可以访问$ _FILES,我们可以将它作为普通文件从那里上传。我在这里想念的是什么?

1 个答案:

答案 0 :(得分:1)

尝试使用CurlFile

发送文件
$filePath= $_FILES['file1']['tmp_name'];
$fileType= $_FILES['file1']['type'];
$fileName= $_FILES['file1']['name'];
$post_data['certf'] = new \CurlFile($filePath, $fileType, $fileName);

$url = "example.com/app_handler.php?key=key";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, "Content-Type:multipart/form-data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
curl_close($ch);
echo $result;