首页 > 解决方案 > 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");

标签: php

解决方案


方法一:服务文件下载

服务器 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);

推荐阅读