Uploading file through FTP using PHP - php

I'm curious how to upload file through FTP using PHP. Let's say I have upload form and user have uploaded a file. How to transfer the file (without moving from temp directory) to some FTP host using PHP?

Here you go:
$ftp = ftp_connect($host, $port, $timeout);
ftp_login($ftp, $user, $pass);
$ret = ftp_nb_put($ftp, $dest_file, $source_file, FTP_BINARY, FTP_AUTORESUME);
while (FTP_MOREDATA == $ret)
{
// display progress bar, or something
$ret = ftp_nb_continue($ftp);
}
// all done :-)
Error handling omitted for brevity.
Please note: you have to have ext-ftp installed and enabled.

Here is a code sample
$ftp_server="";
$ftp_user_name="";
$ftp_user_pass="";
$file = "";//tobe uploaded
$remote_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";
exit;
} else {
echo "There was a problem while uploading $file\n";
exit;
}
// close the connection
ftp_close($conn_id);

How about FTP upload via Curl? (Note: you can also use curl for SFTP, FTPS)
<?php
$ch = curl_init();
$localfile = '/path/to/file.zip';
$remotefile = 'filename.zip';
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://ftp_login:password#ftp.domain.com/'.$remotefile);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);
if ($error_no == 0) {
$error = 'File uploaded succesfully.';
} else {
$error = 'File upload error.';
}
?>

Here's a function to do it for you.
function uploadFTP($server, $username, $password, $local_file, $remote_file){
// connect to server
$connection = ftp_connect($server);
// login
if (#ftp_login($connection, $username, $password)){
// successfully connected
}else{
return false;
}
ftp_put($connection, $remote_file, $local_file, FTP_BINARY);
ftp_close($connection);
return true;
}
Usage:
uploadFTP("127.0.0.1", "admin", "mydog123", "C:\\report.txt", "meeting/tuesday/report.txt");

For anyone want to show a the upload progress while doing file transfers, this is a great library php-ftp-client to start :
The code
$interval = 1;
$ftp->asyncDownload('illustrations/assets.zip', 'assets.zip', function ($stat) use ($interval) {
ob_end_clean();
ob_start();
echo sprintf(
"speed : %s KB/%ss | percentage : %s%% | transferred : %s KB | second now : %s <br>",
$stat['speed'],
$interval,
$stat['percentage'],
$stat['transferred'],
$stat['seconds']
);
ob_flush();
flush();
}, true, $interval);
Result in the browser :

FTP password must be in single quote otherwise it will not accept special characters
$ftp_server="";
$ftp_user_name="";
$ftp_user_pass=''; // this is the right way
$file = "";//tobe uploaded
$remote_file = "";

Related

SFTP file is not downloaded completelly with ssh2.sftp and fread

I am working on a log file download for a separate system that requires SFTP for viewing logs. I am able to view the available log files on the server and download them. My issue is that it seems that the download stops at 2K which, in most cases, is only the first 10 lines of the log file. The files should contain thousands of lines as they are daily logs of changes made to the system.
I have done this in two separate files, one loads all of the files onto a page where the user can select the available log files and click a link to view the contents in the browser:
$ftp_server = "IP of Server";
$ftp_user_name = "USERNAME";
$ftp_user_pass = "PASSWORD";
$connection = ssh2_connect($ftp_server, 22);
ssh2_auth_password($connection,$ftp_user_name, $ftp_user_pass);
$sftp = ssh2_sftp($connection);
$dh = opendir("ssh2.sftp://$sftp//EMSftp/audit_files/");
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..'){
if (strpos($file,"2017-04")){
echo '/EMSftp/audit_files/'.$file.' | curl
| view<br>';
}
}
}
closedir($dh);
I have tried to download the files two different ways using sftp and ssh2:
$file = $_GET['file'];
$local_file = "/var/www/uploads/logs/$file";
if (!file_exists($local_file)){
$connection = ssh2_connect($ftp_server, 22);
ssh2_auth_password($connection,$ftp_user_name, $ftp_user_pass);
$sftp = ssh2_sftp($connection);
$stream = #fopen("ssh2.sftp://$sftp//EMSftp/audit_files/$file", 'r');
if (! $stream)
throw new Exception("Could not open file: $remote_file");
$contents = fread($stream, filesize("ssh2.sftp://$sftp//EMSftp/audit_files/$file"));
file_put_contents ($local_file, $contents);
#fclose($stream);
}
echo '<pre>';
echo file_get_contents($local_file);
echo '</pre>';
and also tried to accomplish this using curl. This only creates a blank file. Not sure what is missing here. Unable to add the file contents to the file.
$file = $_GET['file'];
$local_file = "/var/www/uploads/logs/$file";
fopen($local_file, 'w+');
chmod($local_file, 0777);
$remote = "sftp://$ftp_user_name:$ftp_user_pass#$ftp_server//EMSftp/audit_files/$file";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $remote);
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($curl, CURLOPT_USERPWD, "$ftp_user_name:$ftp_user_pass");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$somecontent = curl_exec($curl);
if (is_writable($local_file)) {
if (!$handle = fopen($local_file, 'a')) {
echo "Cannot open file ($local_file)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($local_file)";
exit;
}
echo "Success, wrote ($somecontent) to file ($local_file)";
fclose($handle);
} else {
echo "The file $local_file is not writable";
}
curl_close($curl);
Not sure where I am missing something. Wondering if there is a time out related to this procedure that I am overlooking. Any help?
This is wrong:
$contents = fread($stream, filesize("ssh2.sftp://$sftp//EMSftp/audit_files/$file"));
It does not guarantee you, that a whole file will be read.
As documented:
fread() reads up to length bytes
If the logs are of reasonable size, use simple file_get_contents:
$contents = file_get_contents("ssh2.sftp://$sftp//EMSftp/audit_files/$file");
If not, read the file in chunks in a loop:
$stream = #fopen("ssh2.sftp://$sftp//EMSftp/audit_files/$file", 'r');
while (!feof($stream))
{
$chunk = fread($stream, 8192);
// write/append chunk to a local file
}
#fclose($stream);

error in upload file to ftp with ftp_nb_fput

I wrote this code for upload file via ftp.
<?php
$file = 'index.php';
$fp = fopen($file, 'r');
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// Initate the upload
$ret = ftp_nb_fput($conn_id, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {
// Do whatever you want
echo ".";
// Continue upload...
$ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
echo "There was an error uploading the file...";
exit(1);
}
fclose($fp);
?>
and I get this error:
Warning: ftp_nb_fput(): Could not open data connection to port 2804: Connection refused
I disable my firewall but not work!
Try running in pasv mode, ftp_pasv($conn_id, true); Also please use ftp_close($conn_id) when you're done.
Thanks Ohgodwhy!

Upload file through FTP using PHP

I'm curious how to upload file through FTP using PHP. Let's say I have SQL function and it will return a filename (dynamic name) and upload file using the return of filename. how can i do this?
i have try before and try in command prompt. but the error is "PHP Warning: ftp_put : failed to open stream: no such file or directory in ...."
my code :
<?php
$db = pg_connect("host=localhost port=5432 dbname=automationReporting user=postgres password=admin") or die("gagal konek.");
/$query = pg_query($db, "select lookup_cell();");
$arr = pg_fetch_array($query, 0, PGSQL_NUM);
$file = $arr[0].'.csv';
$remote_file = '/nury/'; // <-- my directory on server
$ftp_server = '192.168.1.128';
$ftp_user_name = 'polban';
$ftp_user_pass = 'polban2014';
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// Passive mode
// ftp_pasv ($conn_id, true);
$ftp = ftp_put($conn_id, $remote_file, $file, FTP_ASCII);
//var_dump($ftp); die();
// upload a file
if ($ftp) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
?>
Remove the comment for Passive mode and then try once it will work.
<?php
$db = pg_connect("host=localhost port=5432 dbname=automationReporting user=postgres password=admin") or die("gagal konek.");
/$query = pg_query($db, "select lookup_cell();");
$arr = pg_fetch_array($query, 0, PGSQL_NUM);
$file = $arr[0].'.csv';
$remote_file = '/nury/'; // <-- my directory on server
$ftp_server = '192.168.1.128';
$ftp_user_name = 'polban';
$ftp_user_pass = 'polban2014';
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// Passive mode
ftp_pasv ($conn_id, true);
$ftp = ftp_put($conn_id, $remote_file, $file, FTP_ASCII);
//var_dump($ftp); die();
// upload a file
if ($ftp) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
?>

download file from ftp using php file size issue

I have to download files from linkshare server to my server by using cron.
Every thing is perfect if the file size is less then 2 GB but if exceeds it fails to download.
code is given below
$ftp_server = "***.*******.com";
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
$login_result = ftp_login($conn_id, '******', '*******');
$ret = ftp_nb_get($conn_id, $localfile, $serverfile, FTP_BINARY);
while ($ret == FTP_MOREDATA) {
// Do whatever you want
echo ".";
// Continue downloading...
$ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
echo "There was an error downloading the file...";
exit(1);
}
Thanks in advance
This is my code for get all files from link share ftp
<?php
session_start();
$i = $_REQUEST['i'];
if($i==""){
$i=0;
$source_dir=("linkshare");
$source_folder=dir($source_dir);
while($files_list=$source_folder->read())
{
if ($files_list!= "." && $files_list!= "..")
{
$pat="linkshare/";
unlink($pat.$files_list);
}
if($files_list!="")
{
$pat="linkshare/";
unlink($pat.$files_list);
}
}
}
$destinationnameeeeee = "linkshare/";
ini_set("max_execution_time",300000000000000000);
$ftp_server = ''; //ftp server name
$ftp_user_name = ''; //ftp user name
$ftp_user_pass = ''; //ftp user password
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
$source_folder = ftp_nlist($conn_id, ".");
foreach($source_folder as $folder_list)
{
$folderlisting = explode("_",$folder_list);
$folders_list[]= $folder_list;
}
$_SESSION['folder_list'] = $folders_list;
//print_r($folders_list);
$folder_count=count($_SESSION['folder_list']);
$cur_folder = $_SESSION['folder_list'][$i];
$source_file = str_replace('.lmp', '', $_SESSION['folder_list'][$i]);
$destination_file = $destinationnameeeeee.str_replace('.lmp', '', $_SESSION['folder_list'][$i]);
echo $destination_file;
if ((!$conn_id) || (!$login_result))
{
echo "<br />FTP connection has failed!";
echo "<br />Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
}
else
{
echo "<br />Connected to $ftp_server, for user $ftp_user_name";
}
// download the file
$download = ftp_get($conn_id, $destination_file, $source_file, FTP_BINARY);
// check download status
if (!$download)
{
echo "<br />FTP download has failed!";
}
else
{
echo "<br />Downloaded $source_file from $ftp_server as $destination_file";
//if($i<=$folder_count)
if($i>=0)
{
$i=$i+1;
}
if($i==8)
{
exit; // 8 file only now download if you want to extent yourself
}
header("Location:ftpget.php?i=$i");
}
ftp_close($conn_id);
?>
I can load same file for after every file downloading time.
tryfollowing this link, it could help you
runtime behavior for the FTP connection

ftp_get will not download image

$fp = 'test.png';
$server_file = "dir/testing.png";
//-- Connection Settings
$ftp_server = 'ftp.net';; // Address of FTP server.
$ftp_user_name ='user'; // Username
$ftp_user_pass = 'password'; // Password
// set up basic connection
$conn_id = ftp_connect($ftp_server,21);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
$mode = ftp_pasv($conn_id, TRUE);
$download=ftp_get($conn_id, $fp, $server_file, FTP_BINARY);
// try to download $server_file and save to $local_file
if ( $download) {
echo "Successfully $fp\n";
} else {
echo "There was a problem\n";
}
ftp_close($conn_id);
When I run this it says it is successfully, but will not write or download the file.
If I echo file_get_contents($fp); then it will display the image deconstructed into text [in the Web browser]
In need to download images and video...
Try adding
header('Content-Type: image/png');

Categories