首页 > 解决方案 > php使用curl发布数据

问题描述

post.php当我使用 ajax 发布数据并通过 curl发送到时,$_FILES变量为空并获取$_POST变量中的数据。当我打印$_POSTvar 获取以下数据时post.php

   [temp_upload_file] => @/tmp/php6OHgQc;filename=Penguins.jpg;type=image/jpeg

当我打印 "$_FILES" var 在 post.php 上获取空数据时

Array
(
)  

代码:

$url = "post.php";
$ch = curl_init($url);
// send a file
curl_setopt($ch, CURLOPT_POST, true);

$data = array('temp_upload_file' =>'@'.$_FILES['uploadfile']['tmp_name'].';filename='.$_FILES['uploadfile']['name'].';type='. $_FILES['uploadfile']['type']);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// output the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
echo curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

我在这里做错了什么?

先感谢您

标签: phpcurl

解决方案


对于 php5.5+,您需要使用一个新的 curl_file_create() 函数,现在不推荐使用 @ 格式。

尝试使用以下代码:

$url = "post.php";
$tmpfile = $_FILES['temp_upload_file']['tmp_name'];
$filename = basename($_FILES['temp_upload_file']['name']);

$ch = curl_init($url);
// send a file
curl_setopt($ch, CURLOPT_POST, true);

$data = array(
    'uploaded_file' => curl_file_create($tmpfile, $_FILES['uploadfile']['type'], $filename)
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// output the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
echo curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

推荐阅读