从不同的服务器下载php文件

时间:2015-03-13 07:40:09

标签: php ssh2-sftp

我的应用程序位于服务器A和其他服务器服务器B上的数据库中。 用mysql outfile进入Server B的/ tmp目录 我想在服务器A上使用php代码下载此文件

<?php
     $fullpath = '/tmp/users.csv';

     Mysql SELECT ......INTO OUTFILE '$fullpath'
     FIELDS TERMINATED BY ','
     ENCLOSED BY '\"'
     ESCAPED BY '\"'
     LINES TERMINATED BY '\n'

     $connection = ssh2_connect('serverb', 22);
     ssh2_auth_password($connection, 'username', 'password');

     if(ssh2_scp_recv($connection, $fullpath, $fullpath)) {
        echo $filepath.' copied to server!!';
     }
    $filename1 = 'users.csv';

    $mm_type="application/csv"; 
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header('Content-Type: application/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="'.$filename1.'"');
    header("Content-Transfer-Encoding: binary\n");
    readfile($fullpath);
    exit;
?>

使用mysql选择保存在服务器B中的outfile文件,但无法从运行php代码的服务器A下载 此致

2 个答案:

答案 0 :(得分:1)

您还可以尝试“fputcsv”功能以CSV格式下载数据。 您可以像在应用程序中一样连接数据库

$filename = 'users.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$filename.'.csv');
ob_clean();

$output = fopen('php://output', 'w');

fputcsv($output, array('Column1', 'Column2'));

$exceldata = $this->ModelName->query("SELECT field1, field2 from TableName");
// loop over the rows, outputting them
foreach($exceldata as $exceldataval){
 fputcsv($output, $exceldataval);
}

fclose($output);
exit;

答案 1 :(得分:0)

您还可以使用SCP命令将文件从serverA移动到ServerB

scp destination_server_username @IP地址:/path/filename.zip usource_server_username @IP:/path/file.zip