I was asked to write a script to auto FTP a file up onto a server at a particular time everyday.
Writing the script to FTP file onto server is simple, and the auto upload will have to be set in the cron job.
Here is the script to FTP file. Basically what this script does is query data from database, export into CSV file, and then FTP onto the server.
<?php
$host = “localhost”; //database location
$user = “root”; //database username
$pass = “”; //database password
$db_name = “ftp-upload”; //database name
//database connection
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db_name);
//set the file to be writable.
//you may rename the file accordingly, or a unique file name which is auto generated
$fp = fopen(’exportfile.csv’, “w”);
//modify this query as you like
$res = mysql_query($cmd=”SELECT * FROM form’”);
// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
//if there is no record, the file will still be generated but there’s no record available
if($row>0) {
$line = “”;
$comma = “”;
foreach($row as $name => $value) {
$line .= $comma . ‘”‘ . str_replace(’”‘, ‘”"‘, $name) . ‘”‘;
$comma = “,”;
}
$line .= “\n”;
fputs($fp, $line);
// remove the result pointer back to the start
mysql_data_seek($res, 0);
// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {
$line = “”;
$comma = “”;
foreach($row as $value) {
$value=stripslashes($value);
$line .= $comma . ‘”‘ . str_replace(’”‘, ‘”"‘, $value) . ‘”‘;
$comma = “,”;
}
$line .= “\n”;
fputs($fp, $line);
}
} //close for if $row>0
fclose($fp);
$server=”;
$ftp_user_name=”;
$ftp_user_pass=”;
$connection = ftp_connect($server);
$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);
if (!$connection || !$login) { die(’Connection attempt failed!’); }
$upload = ftp_put($connection, ‘upload-ftp.csv’, ‘upload-ftp’.csv’, FTP_BINARY);
if (!$upload) { echo ‘FTP upload failed!’; }
ftp_close($connection);
?>
Hope this simple script will be useful to you! Set a time to run this script in your cron job, and the file will be executed at a particular time to FTP over the file.



Home
May 24th, 2009 at 3:33 am
Hi, nice posts there
thank’s for the interesting information