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
Related
I need to write a script that will download the XML from FTP copied files to the server that will be added to the database by the script. The problem is that I do not know if it is possible to connect to the server where the database is placed and copy files to a folder from which they can be downloaded?
The database is installed on synology MariaDB 10 (localhost via UNIX socket).
<?php
$ftp_serwer = "xxx";
$ftp_nazwa_uzytkownika = "xxx";
$ftp_haslo = "xxx";
// nawiązanie połączenia lub zakończenie działania skryptu
$conn_id = ftp_connect($ftp_serwer) or die("Nie można połączyć się z $ftp_serwer");
// próba logowania
if (#ftp_login($conn_id, $ftp_nazwa_uzytkownika, $ftp_haslo)) {
echo "Połączony jako $ftp_nazwa_uzytkownika#$ftp_serwer\n";
} else {
echo "Nie można zalogować się jako $ftp_nazwa_uzytkownika\n";
}
// nawiązanie połączenia z baza danych msql
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "zlecenia";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, 3307);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// define some variables
$local_file = 'Z:\htdocs\phpmysql\TEST\CRM\localfile\yahootable.xml';
$server_file = '/TU WGRYWAC DANE/yahootable.xml';
// set up basic connection
$conn_id = ftp_connect($ftp_serwer);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_nazwa_uzytkownika, $ftp_haslo);
// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
$sql = "LOAD DATA LOCAL INFILE
'Z:/htdocs/phpmysql/TEST/CRM/localfile/yahootable.xml'
INTO TABLE
yahootable
CHARACTER SET 'utf8'
LINES STARTING BY '<row>' TERMINATED BY '</row>'
(#tmp)
SET
id = ExtractValue(#tmp, '//id'),
various = ExtractValue(#tmp, '//various'),
message = ExtractValue(#tmp, '//message')
";
// zamknięcie połączenia
ftp_close($conn_id);
mysqli_close($conn);
?>
So my questions are:
Where do I have to upload a file so that the server can download it using
LOAD DATA INFILE?
How to copy files to this folder using a script?
When you use the LOCAL keyword in your LOAD DATA LOCAL INFILE command it will load the file from the host where the MySQL client is running, as described on https://dev.mysql.com/doc/refman/8.0/en/load-data.html:
If LOCAL is specified, the file is read by the client program on the client host and sent to the server. The file can be given as a full path name to specify its exact location. If given as a relative path name, the name is interpreted relative to the directory in which the client program was started.
The MySQL client in your case will be the host which runs the php script. The path has to be accessible by that host and will automatically be transferred to the MySQL server.
This question already has answers here:
PHP: How to check if image file exists?
(22 answers)
Closed 5 years ago.
Can someone please help me to make this script check if the file exists, before it truncate the table.
If filename not exists, I want to stop the import.
<?php
//set the connection variables
$hostname = "host";
$username = "username";
$password = "pass";
$database = "database";
$filename = "filename.csv";
//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));
mysqli_query($connection, "TRUNCATE TABLE `my_tablename`");
// open the csv file
$fp = fopen($filename,"r");
//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
//insert csv data into mysql table
$sql = "INSERT INTO Pristabell (Produkt, Pris, Rabattkr, Rabattprosent, Lagerstatus, Butikk, TAGS) VALUES('" . implode("','",$row) . "')";
if(!mysqli_query($connection, $sql))
{
die('Error : ' . mysqli_error($conection));
}
}
fclose($fp);
//close the db connection
mysqli_close($connection);
?>
Thanks :-)
http://php.net/manual/en/function.file-exists.php
if(file_exists($pathtofile)){
//do import
}else{
//stop
}
One simple solution is use
file_exist;
in an if() chunk.
Before the while(), if true continue else exit or trow an exception.
I wrote a php script which fetches the data from file server,it lists all the uploaded file on server.
Now problem is there is large no. of file on my server ,i want limited results per page how can i implement pagination for this.
My php code is :
$ftp_server = "ftp.abc.com";
$ftp_user = "uploads#abc.com";
$ftp_password = "xyz";
$conn = ftp_connect($ftp_server) or die("could not connect to ftp server");
if (ftp_login($conn, $ftp_user, $ftp_password)) {
$contents = ftp_nlist($conn, $path);
foreach($contents as $value) {
$i++;
echo "$i <a href='#form' id='url_title' class='links'>$value</a><br><br> <br>";
}
}
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);
?>
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.