如何使用curl使用curl上传文件

Had*_*i44 67 php upload curl

我想知道如何使用cURL或PHP中的任何其他内容上传文件.我在谷歌搜索了很多次但没有结果.

换句话说,用户在表单上看到一个文件上传按钮,表单被发布到我的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>';
}
Run Code Online (Sandbox Code Playgroud)

我希望代码将文件发送到接收器文件.

小智 135

使用:

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);
Run Code Online (Sandbox Code Playgroud)

你也可以参考:

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

  • 也许,使用curl的内置功能是更好的方法:http://www.php.net/manual/es/function.curl-file-create.php.当然,你可以使用POSTFIELDS的方式并用`@`填充前面的值.无论如何,asnwer是从博客的curl自定义用法复制而来的.正确的答案是,`@`char将其定义为文件,而不是var.$ post将包含`@ filename.jpg`作为示例. (8认同)
  • @fiXedd我目前正在使用php 5.6,并且需要使用`curl_file_create`(由karthik提供的sollution不起作用).所以代码应该升级为这样的东西:`if function_exists('curl_file_create')){$ cFile = curl_file_create($ dest); } else {$ cFile ='@'.真实路径($ DEST); }` (8认同)
  • 该解决方案在 php 5.6 中停止工作,解决方案是将文件添加为: new CURLFile(realpath($fileName)); (3认同)
  • @erm3nda 那只是 PHP 5.5+。 (2认同)
  • 什么是`extra_info => 123456`用于什么? (2认同)

8ct*_*pus 7

对于使用 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;
}
Run Code Online (Sandbox Code Playgroud)

从 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;
}
Run Code Online (Sandbox Code Playgroud)

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