如何使用带有 PHP 的 curl 上传文件

问题描述 投票:0回答:2

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

换句话说,用户在表单上看到一个文件上传按钮,表单被发布到我的 PHO 脚本,然后我的 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>';
}

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

php curl upload
2个回答
183
投票

用途:

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);


0
投票

对于那些使用 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

© www.soinside.com 2019 - 2024. All rights reserved.