saving mysql query as csv file on remote ftp server using php - php

I am trying to export a MySQL query result to a remote ftp server.
I have the below code but I am currently getting an error:
Warning: ftp_put() [function.ftp-put]: Opening ASCII mode data connection. in /home/hulamyxr/public_html/kisv2/xmltest/export.php on line 50
I would think that my $file = $csv_filename; might be the issue as this is fetching the csv file that has just been created on my local server?
any ideas?
My syntax is:
<?php
$host = 'localhost';
$user = 'un';
$pass = 'pwd';
$db = 'dbname';
$table = 'v2ReportingTable';
$file = 'export';
$datetime=date("Y-m-d H:i:s");
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
//Create a CSV for
$result = mysql_query("SELECT * FROM dbname.v2ReportingTable");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$csv_filename = "export-" .$datetime.".csv";
$fp = fopen($csv_filename, 'w+');
if ($fp && $result)
{
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
//works till here
$ftp_server = "ftp.server.co.za";
$ftp_user_name = "un";
$ftp_user_pass = "pw";
$file = $csv_filename;
$remote_file = "/LocExports/".$file;
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
?>
Thanks Again

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:
<?php
ftp_pasv($resource, true);
?>

Related

Updating CSV file in FTP server in PHP [duplicate]

This question already has answers here:
Transfer in-memory data to FTP server without using intermediate file
(2 answers)
Closed 3 years ago.
I'm trying to updating a CSV file which in a external FTP server, I tried to follow the basic ftp_fput() but it's not working. File is not updating and also a blank CSV file is downloading when I run this script which is not needed. I've been trying to solve this but can't find the solution
<?php
// connect and login to FTP server
//ftp setup
$ftp_server = "ftp.test.test.co.uk";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$ftp_username='ftp_username';
$ftp_userpass='ftp_userpass';
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
//local DB setup
$servername = "localhost";
$username = "root";
$password = "TEST";
$dbname= "TEST";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//END database connection//
$sql = "SELECT sku,SUM(quantity) as quantity FROM tbl_old_books GROUP BY isbn";
$result = $conn->query($sql);
header("Content-Disposition: attachment; filename=AllOpenOrders.csv");
header("Content-Type: application/csv; ");
// file creation
$file = fopen('php://temp', 'W');
$header = array("SKU","QUANTITY");
fputcsv($file, $header);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
fputcsv($file, $row );
}
}
$remote_path = "/export/AllOpenOrders.csv";
ftp_fput($ftp_conn, $remote_path, $file, FTP_BINARY, 0);
fclose($file);
ftp_close($ftp_conn);
?>
You file handler $file points at the end of the file as you write in it. There is nothing left to write via ftp_fput.
You can reset your file pointer at the beginning of the file with rewind($file); before writing in the FTP : rewind documentation

how to get file from ftp server and copy on own server

I want to get file from client server and copy them on my server , I have successfully connected to client server, my code is below.
// connect and login to FTP server
$ftp_server = "xx.xxx.xxx.xxx";
$ftp_username = 'xxxxxxxxxxxxxxx';
$ftp_userpass = 'xxxxxxxxxxxxxxxx';
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
echo "<pre>";
print_r($login);
echo "</pre>";
// get the file list for /
$filelist = ftp_rawlist($ftp_conn, "/");
// close connection
ftp_close($ftp_conn);
echo "<pre>";
print_r($filelist);
echo "</pre>";
// output $filelist
var_dump($filelist);
May anyone please advise how can I achieve this?
You can use the ftp_fget function specified here: http://php.net/manual/en/function.ftp-fget.php
(ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer.)
Here an example provided by the documentation:
<?php
// path to remote file
$remote_file = 'somefile.txt';
$local_file = 'localfile.txt';
// open some file to write to
$handle = fopen($local_file, 'w');
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// try to download $remote_file and save it to $handle
if (ftp_fget($conn_id, $handle, $remote_file, FTP_ASCII, 0)) {
echo "successfully written to $local_file\n";
} else {
echo "There was a problem while downloading $remote_file to $local_file\n";
}
// close the connection and the file handler
ftp_close($conn_id);
fclose($handle);
?>
This is how I resolved this now all files will copy on your server. use ftp_ssl_connect if its secure
$ftp_server = "xx.xxx.xxx.xxx";
$ftp_username = 'xxxxxxxxxxxxxx';
$ftp_userpass = 'xxxxxxxxxxxxxxxxxxx';
$ftp_conn = ftp_ssl_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
ftp_pasv($ftp_conn,pasv);
$output_directory="files1/ftpgetfiles/137/";
// get the file list for /
$filelist = ftp_nlist($ftp_conn, "/");
foreach ($filelist as $key => $value) {
$fp = fopen($output_directory.$value,"w");
if(ftp_fget($ftp_conn, $fp, $value, FTP_BINARY))
{
fclose($fp);
}
}
ftp_close($ftp_conn);

can't download file from ftp with ftp_get (no error)

I'm trying to download file from ftp, but whatever i tried i couldn't download any file from ftp and it is not giving any error.
My code fetching file names from database and compares these file names with existing ftp file(names). If file name exist on ftp i want to download this file to my local-destination folder.
I can read ftp file names but i can't download them. Hope you can help me.
Here is my code
error_reporting(E_ALL);
$ftp_server = "xx.xx.y12.34"; //server
$bt = ftp_connect($ftp_server); // connect to ftp
$username = "myusername"; $pass = "mypass"; //username and password
$connection = ftp_login($bt, $username, $pass); // login ftp with username and password
ftp_pasv($bt, true);
if ((!$bt) || (!$connection)) {
echo "failed";
exit;
}else {
$path = "/1_Swatch Files/LG Swatches/";
$destination_folder = "/home/faruk/lasenza/media/color_samples/";
// mysql connection codes..
$results = $readConnection->fetchAll($query); // fetch file names from database
$contents_on_server = ftp_nlist($bt, $path);
foreach($results as $result){
$check_file_exist = $result["CLR_CODE"].".gif";
if(in_array($check_file_exist, $contents_on_server)) {
$server_file = $result["CLR_CODE"].".gif";
if (ftp_get($bt, $destination_folder , $server_file, FTP_BINARY)) {
echo 'Succeeded';
}else{
echo "There was a problem";
}
break;
}
}
}

Search through multiple directories for files PHP

New to php. I need to search through multiple directories on an ftp server and download files contained in them according to their date (which is contained in each file's name). So far I am running into issues with Array to string conversion - hopefully you can see what I am "trying" to do here and might be able to help me out.
<?php
$url = ' MY FTP SERVER';
$user = ' USERNAME ';
$pass = ' PASSWORD';
$target = 'LOCAL DIRECTORY';
$connection = ftp_connect($url) or die ("Could not connect to $url");
$loginBool = ftp_login($connection, $user, $pass);
if ($loginBool)
{
echo "Connected as $user at $url";
}else{
echo "Could not connect as $user";
}
ftp_chdir($connection, 'MOVE ONE FOLDER IN');
$ftpDirectories = ftp_nlist($connection, ".");
for($i=0; $i < (count($ftpDirectories)); $i++){
$directory = ("/MAIN DIR/$ftpDirectories[$i]/");
echo $directory;
ftp_chdir($connection, $directory);
echo ftp_nlist($connection, $directory);
}
?>
The logic, as I see it, works as follow:
Get a listing of all folders under the main folder which is stored in Array
Loop through each element of the array(folders on the ftp)and change into the directory
one by one
Print out the files (so I know its working)
What I still need to add:
After changing into a directory split the filenames into an array and compare them to
today's date -> download if the filenameDate[index] == today's date
THANK YOU FOR YOUR HELP!
EDIT
<?php
$url = 'pmike86.zxq.net';
$user = 'pmike86_zxq';
$pass = '******';
$target = 'C:\Folder\\';
$connection = ftp_connect($url) or die ("Could not connect to $url");
$loginBool = ftp_login($connection, $user, $pass);
if ($loginBool)
{
echo "Connected as $user at $url";
}else{
echo "Could not connect as $user";
}
ftp_chdir($connection, 'HW');
$ftpDirectories = ftp_nlist($connection, ".");
for($i=0; $i < (count($ftpDirectories)); $i++){
$directory = ("/HW/$ftpDirectories[$i]/");
echo $directory;
ftp_chdir($connection, $directory);
foreach (ftp_nlist($connection, $directory) as $item)
{
ftp_get($connection, $target, $item, FTP_BINARY);
}
}
?>

Export to CSV PHP as a Download File

I am using a CSV file to export a mysql table. How can I view it as a download file now that it is stored on Drive C: directly without any notification
<?php
$host = 'localhost'; // <-- db address
$user = 'root'; // <-- db user name
$pass = 'root'; // <-- password
$db = 'urs'; // db's name
$table = 'veiwresult'; // table you want to export
$file = 'alaa'; // csv name.
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query(" SELECT ApplicantNum,name, averg,choice FROM veiwresult");
fputcsv($f, array('ApplicantNum','name','averg', 'choice'));
$timestamp = date('Ymd-His');
$f = fopen("C:/mycsv-{$timestamp}.csv", 'w');
// Headers
while($row = mysql_fetch_row($result))
{
fputcsv($f, $row);
}
fputcsv($f, $items_array);
fclose($f);
?>
If you want to store csv-file and then open it without any clicking, it`s impossible.
If you just wish to have it opened, open it in browser window via
header('Content-disposition: inline;filename=foobar.csv');
header('Content-Type: text/csv;charset=UTF-8');
echo $csv_content;
where $csv_content is a string with contents of csv-file. You cat get it this way
$csv_content = file_get_contents('c:/mycsv.csv');
To download it...
<?php
$host = 'localhost'; // <-- db address
$user = 'root'; // <-- db user name
$pass = 'root'; // <-- password
$db = 'urs'; // db's name
$table = 'veiwresult'; // table you want to export
$file = 'alaa'; // csv name.
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query(" SELECT ApplicantNum,name, averg,choice FROM veiwresult");
fputcsv($f, array('ApplicantNum','name','averg', 'choice'));
$timestamp = date('Ymd-His');
$f = fopen("C:/mycsv-{$timestamp}.csv", 'w');
// Headers
while($row = mysql_fetch_row($result))
{
fputcsv($f, $row);
}
fputcsv($f, $items_array);
fclose($f);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="mycsv-{$timestamp}"');
readfile('C:/mycsv-{$timestamp}.csv');
?>
This will still notify the user of the download, and depending on their settings they may need to accept the download. This functionality cannot be overridden of course.

Categories