如何将图像移动到另一台服务器PHP

时间:2018-11-16 02:57:46

标签: php curl

我有两台服务器,所以我想从第一台服务器上传文件/图像时(使用移动上传文件功能), 文件应上传到第二台服务器。为此,我使用了以下代码

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@/path/to/file.txt'));
curl_setopt($ch, CURLOPT_URL, 'http://server2/upload.php');
curl_exec($ch);
curl_close($ch);

但是我想知道第二台服务器“ upload.php”中应该包含什么代码。我该如何提及路径?

1 个答案:

答案 0 :(得分:0)

首先,不要尝试使用@方法上传文件,它在PHP5.5中已弃用,在PHP5.6中默认禁用,并在PHP7.0中已完全删除 。使用CURLFile上传文件。要提及路径,只需将路径添加为数组中的另一个post变量。至于接收者,请阅读php.net上的handling file uploads in php article。最后,考虑是否要让找到该URL的任何人都可以上传任何文件。 (可能不是,您*可能*想要在上传时设置密码),例如

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'file' => new CURLFile('path/to/file.jpg'),
    'path' => '/where/ever/you/want.jpg',
    'password' => 'd540cyLp419rdwelv8c-'
));

在发件人上

if (! hash_equals(hash('sha256', 'd540cyLp419rdwelv8c-', true), hash('sha256', (string) ($_POST['password'] ?? ''), true))) {
    http_response_code(403); // forbidden
    die("wrong/missing password.");
}
$upload_path = $_FILES["file"]["tmp_name"];
$requested_file_path = $_POST['path'];

在接收器上,再次请参见前面的“在php中处理文件上传”文章以了解更多信息。