php文件从一台服务器传输到另一台服务器

时间:2020-01-22 10:52:39

标签: php

我需要使用html-php将文件从server1传输到server2。现在,从server1可以使用以下php代码很好地下载文件,但是除了将文件下载到客户端计算机之外,我需要将此文件文件上传到另一台服务器,我该怎么做。

请注意,该文件不在Web目录中,我必须从无Web目录读取文件并将其传输到server2。

        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        flush(); // Flush system output buffer
        readfile("/home/user/file.ini");

1 个答案:

答案 0 :(得分:0)

方法1:提供文件下载

服务器1

            $file_name = 'usb.zip';
            $file = '/usr/download/' . $file_name;
            if (file_exists($file))
            {
                if(false !== ($handler = fopen($file, 'r')))
                {
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename='.basename($file));
                    header('Content-Transfer-Encoding: binary');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($file));
                    //Send Chunks
                    while(false !== ($chunk = fread($handler,4096)))
                    {
                        echo $chunk;
                    }
                }
                exit;
            }

服务器2

file_put_contents("usb.zip", fopen("http://xxx/file.php", 'r'));

方法2:通过SFTP上传

$resFile = fopen("ssh2.sftp://{$resSFTP}/".$csv_filename, 'w');
$srcFile = fopen("/home/myusername/".$csv_filename, 'r');
$writtenBytes = stream_copy_to_stream($srcFile, $resFile);
fclose($resFile);
fclose($srcFile);