我想知道如何使用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);
对于使用 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