2

My application is on Server A and database in on other server Server B. With mysql outfile into /tmp directory of Server B. I want to download this file using php code on Server A

<?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;
?>

with mysql select outfile file saved in Server B, but not able to download from Server A, where php code runs Regards

Aruti
  • 73
  • 6
  • Hey, syntax error ! You can't execute query like this ? – Raptor Mar 13 '15 at 08:29
  • @Raptor; Query executed properly and I get csv file on serverB '/tmp/users.csv'. Here is an example of query SELECT 'First Name','Last Name','User Code' UNION (SELECT fname,lname,ucode FROM csvfields INTO OUTFILE '$fullpath' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\"' LINES TERMINATED BY '\n' ) – Aruti Mar 15 '15 at 09:49

2 Answers2

1

You can also try "fputcsv" function for downloading data in CSV format. You can connect with your Database as you do in your application

$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;
Amit Maan
  • 85
  • 9
0

You can also use SCP command to move file from serverA to ServerB

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