使用cURL发送文件

时间:2012-12-03 05:45:35

标签: php file curl

我已经用cURL发送了一些帖子数据,现在我正在尝试发送文件,一路上迷路了。我正在使用带有文件输入的表单。然后希望cURL将它发送到我的服务器。这是我的上传页面。     <form action="curl_page.php" method="post" enctype="multipart/form-data"> Filename: <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form>

这是我的卷曲页面,其中包含一些问题。

<?php
$tmpfile = $_FILES['file']['tmp_name'];
$filename = basename($_FILES['file']['name']);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://my_server/file_catch.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
    'uploaded_file' => '@'.$tmpfile.';filename='.$filename,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
?>

我服务器上的file_catch.php看起来像这样。

<?php
$folder = "audio/";

$path = $folder . basename( $_FILES['file']['name']);

if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
    echo "The file ".  basename( $_FILES['file']['name']). " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您没有发送通过邮寄请求获得的文件。使用以下代码通过CURL请求发布文件。

$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);

$data = array(
    'uploaded_file' => '@'.$tmpfile.';filename='.$filename,
);

$ch = curl_init();   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)

curl_exec($ch);

有关更多参考,请查看以下链接 Send file via cURL from form POST in PHP