如何使用 PHP 和 curl 上传文件

98

如何在PHP中使用cURL或其他方式上传文件?

换句话说,用户在表单上看到一个文件上传按钮,表单被提交到我的PHP脚本,然后我的PHP脚本需要将其重新发布到另一个脚本(例如在另一台服务器上)。

我有这个代码来接收文件并上传它:

echo"".$_FILES['userfile']."";
$uploaddir = './';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if ( isset($_FILES["userfile"]) ) {
    echo '<p><font color="#00FF00" size="7">Uploaded</font></p>';
    if (move_uploaded_file
($_FILES["userfile"]["tmp_name"], $uploadfile))
echo $uploadfile;
    else echo '<p><font color="#FF0000" size="7">Failed</font></p>';
}

我该如何将文件发送到接收服务器?


5
不用“ftp”,我想用curl发送$_FILES['userfile']中的文件。 - Hadidi44
嗯...现在怎么办?你想把它发送到哪里?你的目标系统是什么? - Till Helge
将源文件(问题中的PHP文件)上传到Linux目标系统。 - Hadidi44
2个回答

191

使用:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

您还可以参考:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

PHP 5.5+的重要提示:

现在我们应该使用https://wiki.php.net/rfc/curl-file-upload,但如果您仍然想使用此过时的方法,则需要设置curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);


9
也许,更好的方法是使用curl的内置功能:http://www.php.net/manual/es/function.curl-file-create.php。当然,你也可以使用POSTFIELDS的方式,以`@`为前缀填充值。无论如何,这个答案是从一个博客中自定义使用curl复制的。正确的答案是说明@字符将其定义为文件,而不是变量。例如,$post将包含@filename.jpg - m3nda
2
@erm3nda 这只适用于PHP 5.5及以上版本。 - Jeremy Logan
10
我目前使用的是 PHP 5.6,并且需要使用curl_file_create(karthik 提供的解决方案无效)。因此,代码应该升级为类似以下的形式:如果 curl_file_create 函数存在,则:$cFile = curl_file_create($dest);否则,使用如下形式:$cFile = '@' . realpath($dest); - Marek Roj
4
extra_info => 123456 用于什么? - Aaron Gillion
3
这个解决方案在 PHP 5.6 中停止有效,解决方法是将文件添加为:new CURLFile(realpath($fileName))。 - Michał Fraś
显示剩余8条评论

6

对于使用 PHP >= 5.5 的用户,可以使用 CURLFile

$curlFile = new \CURLFile('test.txt', 'text/plain', 'test.txt');

$ch = curl_init('http://example.com/upload.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'file' => $curlFile,
]);

$result = curl_exec($ch);

if ($result === false) {
    echo 'upload - FAILED' . PHP_EOL;
}

从 PHP 8.1 开始,仅使用 CURLStringFile 可将文件存储在内存中:

$txt_curlfile = new \CURLStringFile('test content', 'test.txt', 'text/plain');

$ch = curl_init('http://example.com/upload.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'file' => $txt_curlfile
]);

$result = curl_exec($ch);

if ($result === false) {
    echo 'upload - FAILED' . PHP_EOL;
}

参考资料:https://php.watch/versions/8.1/CURLStringFile


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接