Php ftp get file

FTP Functions

I didn’t quite like my FTP program since I had to make all the settings all over when i restarted the client, so I made this script for simple ftp uploading, its running as a CLI app.

//if STDIN isn’t defined, define it
if (! defined ( «STDIN» ))

define ( «STDIN» , fopen ( «php://stdin» , «r» ));

echo «FTP file uploader\r\n\r\n» ;

//trim() all the fgets cause it seams to add a \n
$server = trim ( fgets ( STDIN ));

$username = trim ( fgets ( STDIN ));

$password = trim ( fgets ( STDIN ));

$connect = ftp_connect ( $server );
$login = ftp_login ( $connect , $username , $password );

if( trim ( fgets ( STDIN )) == «Y» )

//enable passive mode
ftp_pasv ( $connect , true );

$showContent = ftp_nlist ( $connect , «» );

//escape the uploading process by typing «exit;»
if ( $file == «exit;» )

//use «$file, $file» since the file shouldn’t be renamed, also if its a binary file change the last argument to FTP_BINARY
$upload = ftp_put ( $connect , $file , $file , FTP_ASCII );

echo «The file \»» . $file . «\» was successfully uploaded. :)\r\nSize of \»» . $file . «\»: » . filesize ( $file ) / 1024 . «kb.\r\n» ;
echo «My work is done, bye.\r\n» ;

After looking everywhere for a «FULLY WORKING» ftp uploader script, I finally came up with this, by using a lot of various one’s I found on the web. If you find a better way of doing something, please let me know. Thanks, and Enjoy

if(isset( $_POST [ ‘SubmitFile’ ])) $myFile = $_FILES [ ‘txt_file’ ]; // This will make an array out of the file information that was stored.
$file = $myFile [ ‘tmp_name’ ]; //Converts the array into a new string containing the path name on the server where your file is.

$myFileName = basename ( $_POST [ ‘txt_fileName’ ]); //Retrieve filename out of file path

$destination_file = «/» . $myFileName ; //where you want to throw the file on the webserver (relative to your login dir)

// connection settings
$ftp_server = «127.0.0.1» ; //address of ftp server.
$ftp_user_name = «Your UserName» ; // Username
$ftp_user_pass = «Your Password» ; // Password

$conn_id = ftp_connect ( $ftp_server ); // set up basic connection
$login_result = ftp_login ( $conn_id , $ftp_user_name , $ftp_user_pass ) or die( «

You do not have access to this ftp server!

» ); // login with username and password, or give invalid user message
if ((! $conn_id ) || (! $login_result )) < // check connection
// wont ever hit this, b/c of the die call on ftp_login
echo «FTP connection has failed!
» ;
echo «Attempted to connect to $ftp_server for user $ftp_user_name » ;
exit;
> else // echo «Connected to $ftp_server, for user $ftp_user_name
«;
>

$upload = ftp_put ( $conn_id , $destination_file , $file , FTP_BINARY ); // upload the file
if (! $upload ) < // check upload status
echo «

FTP upload of $myFileName has failed!

» ;
> else echo «Uploading $myFileName Complete!

Читайте также:  Синтаксис javascript на примерах

» ;
>

ftp_close ( $conn_id ); // close the FTP stream
>
?>

A function to get a remote file and return it’s contents, instead of saving to a local file, was missing — here it is:

function ftp_fetch($ftp_stream, $remote_file) ob_end_flush();
ob_start();
$out = fopen(‘php://output’, ‘w’);
if (!ftp_fget($ftp_stream, $out, $remote_file, FTP_ASCII)) die(‘Unable to get file: ‘ . $remote_file);
fclose($out);
$data = ob_get_clean();
return $data;
>

It works the same as ftp_get(), but instead returns the contents of the remote file — for example:

$ftp = ftp_connect(‘my.server.com’, 21, 60);
ftp_login($ftp, ‘username’, ‘password’);
$data = ftp_fetch($ftp, ‘path/to/remote.file’);
echo $data;

Note, I use it to fetch text-files from a server — if you need to fetch binary files, change FTP_ASCII to FTP_BINARY .. but most likely, getting files to memory is only useful for smaller files, e.g. plain text, xml, etc.

This took me a few hours to work out. It is based on the code below I’ve just added a string replace to convert pathname given by Windows to Unix pathname. Hope it saves somebody some time. Enjoy! (Also, delete file function is included:))

$myFile = $_FILES [ ‘file’ ]; // This will make an array out of the file information that was stored.
$file = $myFile [ ‘tmp_name’ ]; //Converts the array into a new string containing the path name on the server where your file is.
$myFileName = $_POST [ ‘MyFile’ ]; //Retrieve file path and file name
$myfile_replace = str_replace ( ‘\\’ , ‘/’ , $myFileName ); //convert path for use with unix
$myfile = basename ( $myfile_replace ); //extract file name from path
$destination_file = «/» . $myfile ; //where you want to throw the file on the webserver (relative to your login dir)
// connection settings
$ftp_server = «127.0.0.1» ; //address of ftp server (leave out ftp://)
$ftp_user_name = «» ; // Username
$ftp_user_pass = «» ; // Password
$conn_id = ftp_connect ( $ftp_server ); // set up basic connection
// login with username and password, or give invalid user message
$login_result = ftp_login ( $conn_id , $ftp_user_name , $ftp_user_pass ) or die( «

You do not have access to this ftp server!

» );
$upload = ftp_put ( $conn_id , $destination_file , $file , FTP_BINARY ); // upload the file
if (! $upload ) < // check upload status
echo «

FTP upload of $myFileName has failed!

» ;
>
/*
// try to delete $file
if (ftp_delete($conn_id, $destination_file)) echo «$destination_file has been deleted!\n»;
> else echo «Could not delete $destination_file!\n»;
>
*/
ftp_close ( $conn_id ); // close the FTP stream
>
?>

» method=»POST» >
Please choose a file:

It may seem obvious to others, but it had me stumped for nearly an hour! If you can connect to an ftp site but some functions (list, put, get etc) don’t work, then try using ftp_pasv and set passive mode on.

// setup $host and $file variables for your setup before here.

$hostip = gethostbyname ( $host );
$conn_id = ftp_connect ( $hostip );

// login with username and password
$login_result = ftp_login ( $conn_id , $ftp_user_name , $ftp_user_pass );

// IMPORTANT. turn passive mode on
ftp_pasv ( $conn_id , true );

if ((! $conn_id ) || (! $login_result )) echo «FTP connection has failed!» ;
echo «Attempted to connect to $host for user $ftp_user_name » ;
die;
> else echo «Connected to $host , for user $ftp_user_name
» ;
echo «Host IP is $hostip
» ;

Читайте также:  Api java server socket

// upload a file
if ( ftp_put ( $conn_id , $remote_file , $file , FTP_ASCII )) echo «successfully uploaded $file
» ;
> else echo «There was a problem while uploading $file
» ;
>

// close the connection
ftp_close ( $conn_id );
>
?>

I have written an OpenSource ZIP2FTP interface, which actually takes a given ZIP file and decompresses it in the folder on an FTP server you specify.

Therefore it may be quite interesting for you people interested in FTP, its adress is http://zip2ftp.alishomepage.com ; those who directly want the source may visit http://zip2ftp.alishomepage.com/?do=getSource

//If you want to move or replicate the folder hierarchy from your current server to another remote server. Then this will be helpful as this will browse the current server’s directory and at the same time it will copy that file in the remote server in the same directory.

//This script will copy all the files from this directory and subdirectory to another remote server via FTP

function rec_copy ($source_path, $destination_path, $con)
ftp_mkdir($con, $destination_path);
ftp_site($con, ‘CHMOD 0777 ‘.$destination_path);
ftp_chdir($con,$destination_path);

// make a FTP connection —VK
$con = ftp_connect(«69.18.213.131»,21);
$login_result = ftp_login($con,»username»,»password»);

// this is the root path for the remote server— VK
$rootpath = «mainwebsite_html»;

// this is the physical path of the source directory. actually u can also use the relative path. — VK
$sourcepath = realpath(«../»).»/resdesk»;

// this directory name will only change the top most directory and not the inner one — VK
$destination_dir_name = «resdesk_».$account_id.»/»;

rec_copy ($sourcepath, $destination_dir_name, $con);
if (function_exists(«ftp_close»))
ftp_close($con);
>
?>

I think what some other posts were trying to say which may need clarification is that in PHP 4.2.3, ftp_connect(«myhost.com») was failing most of the time, except it would work like every few minutes.

The fix is that ftp_connect seems to have a bug resolving addresses. If you do:

$hostip = gethostbyname($host);
$conn_id = ftp_connect($hostip);

It seems to solve the problem.
(Other users referred to an ftpbuf() error. not sure what that is, but this should fix it.)

Here’s a little function that I created to recurse through a local directory and upload the entire contents to a remote FTP server.

In the example, I’m trying to copy the entire «iwm» directory located at /home/kristy/scripts/iwm to a remote server’s /public_html/test/ via FTP.

The only trouble is that for the line «if (!ftp_chdir($ftpc,$ftproot.$srcrela))», which I use to check if the directory already exists on the remote server, spits out a warning about being unable to change to that directory if it doesn’t exist.

But an error handler should take care of it.

My thanks to the person who posted the snippet on retrieving the list of files in a directory.

For the version of the script that echo’s it’s progress as it recurses & uploads, go to: http://pastebin.com/73784

// set the various variables
$ftproot = «/public_html/test/» ;
$srcroot = «/home/kristy/scripts/» ;
$srcrela = «iwm/» ;

Читайте также:  Питон работа с картами

// start ftp’ing over the directory recursively
ftpRec ( $srcrela );

// close the FTP connection
ftp_close ( $ftpc );

// enter the local directory to be recursed through
chdir ( $srcroot . $srcrela );

if ( $handle = opendir ( «.» ))
while ( false !== ( $fil = readdir ( $handle )))
if ( $fil != «.» && $fil != «..» )
// check if it’s a file or directory
if (! is_dir ( $fil ))
<
// it’s a file so upload it
ftp_put ( $ftpc , $ftproot . $srcrela . $fil , $fil , FTP_BINARY );
>
else
// it’s a directory so recurse through it
if ( $fil == «templates» )
// I want the script to ignore any directories named «templates»
// and therefore, not recurse through them and upload their contents
>
else
ftpRec ( $srcrela . $fil . «/» );
chdir ( «../» );
>
>
>
>
closedir ( $handle );
>
>
?>

Here is a FTP-abstraction-class which supports the most commands.

Also it works on TLS, SSLv2 etc. by using stream_crypto_enable()

Many thanks to WEZ at this point after all the years 🙂

Here is an example for downloading a remote ftp structure to local server, useful for migrating sites from one server to another, especially when you are upgrading ensim 😉

connection to a ftp server across proxy

$ftp_server = «proxy»; f.e. 123.456.789.10
$ftp_user_name = «username@ftpserver»; f.e. exampleuk@www.example.uk
$ftp_user_pass = «password»;

$conn_id = ftp_connect($ftp_server, 2121);
$login_result = ftp_login( $conn_id, $ftp_user_name, $ftp_user_pass );

Here’s another FTP interface over PHP (also uses MySQL)

PS: this script will ALSO allow you to download its source. So it becomes interesting for YOU PROGRAMMERS as well 😀

I fixed the below upload script to work with Windows uploads (and updated some of the syntax). I also added a Javascript «progress indicator» for those of us who don’t use PHP 5.2

if(isset( $_POST [ ‘start_upload’ ]) && $_FILES [ ‘txt_file’ ][ ‘name’ ] != «» )

$local_file = $_FILES [ ‘txt_file’ ][ ‘tmp_name’ ]; // Defines Name of Local File to be Uploaded

$destination_file = «/» . basename ( $_FILES [ ‘txt_file’ ][ ‘name’ ]); // Path for File Upload (relative to your login dir)

// Global Connection Settings
$ftp_server = «127.0.0.1» ; // FTP Server Address (exlucde ftp://)
$ftp_user_name = «username» ; // FTP Server Username
$ftp_user_pass = «password» ; // Password

// Connect to FTP Server
$conn_id = ftp_connect ( $ftp_server );
// Login to FTP Server
$login_result = ftp_login ( $conn_id , $ftp_user_name , $ftp_user_pass );

// Verify Log In Status
if ((! $conn_id ) || (! $login_result )) echo «FTP connection has failed!
» ;
echo «Attempted to connect to $ftp_server for user $ftp_user_name » ;
exit;
> else echo «Connected to $ftp_server , for user $ftp_user_name
» ;
>

$upload = ftp_put ( $conn_id , $destination_file , $local_file , FTP_BINARY ); // Upload the File

// Verify Upload Status
if (! $upload ) echo «

FTP upload of » . $_FILES [ ‘txt_file’ ][ ‘name’ ]. » has failed!

» ;
> else echo «Success!
» . $_FILES [ ‘txt_file’ ][ ‘name’ ] . » has been uploaded to » . $ftp_server . $destination_file . «!

» ;
>

ftp_close ( $conn_id ); // Close the FTP Connection
>
?>

window.onload = function() document.getElementById(«progress»).style.visibility = «hidden»;
document.getElementById(«prog_text»).style.visibility = «hidden»;
>

function dispProgress() document.getElementById(«progress»).style.visibility = «visible»;
document.getElementById(«prog_text»).style.visibility = «visible»;
>

Источник

Оцените статью