Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Transfer Files Using FTP in PHP (http://www.go4expert.com/articles/transfer-files-using-ftp-php-t29373/)

pradeep 26Dec2012 06:42

Transfer Files Using FTP in PHP
File Transfer Protocol or popularly known as FTP has been a de facto standard for transferring files for many years, can be used in many programs / utilities like backup programs, etc. PHP is being increasingly used in writing scripts for maintenance and other purposes and the FTP extensions comes real handy in such cases.

In this article we'll be looking at installation and usage of the FTP functions available in PHP.


In case you are using a Debian based system like Ubuntu etc, this simple command will install it for you.


$ sudo apt-get install php-net-ftp

Other Linux systems, you'll need to configure PHP with --enable-ftp option.

Luckily for Windows users, nothing needs to be done as the extension is built-in.


I'll not be covering all possible functions available with the extension, but just the frequently used/needed ones according to me, for a full list of functions and their uses refer to http://php.net/manual/en/ref.ftp.php. Please follow the demo code below, I have commented wherever possible to help understand the usage better.

Code: PHP

// connect to the FTP server
$conn = ftp_connect('');

// login with username / pass, or anonymously as required
$login_res = ftp_login( $conn, 'pradeep', 'anju123' );

// check if the connection and login were successful or not
if($conn && $login_res) {
    print "Yippee!! Connected to FTP";
else {
    print "Connection / Login failed";

// say, we change to a different directory
if(!ftp_chdir( $conn, '/home/pradeep/photos/')) {
    print "Oops! could not change directory";

// get a list of files/directories
// this only returns the names not any details
$basic_listing = ftp_nlist( $conn, "." );

var_dump( $basic_listing );

// get detailed info using raw listing
$raw_listing = ftp_rawlist( $conn, '.' );

var_dump( $raw_listing );

// now we'll upload a file
if (ftp_put( $conn, 'server_image.jpg', 'local_image.jpg', FTP_BINARY)) {
    print "Uploaded an image";

// download a file
if (ftp_get( $conn, 'local_image.jpg', 'server_image.jpg', FTP_BINARY)) {
    print "Downloaded an image";

// delete a file
if (ftp_delete( $conn, 'server_image.jpg' )) {
    print "Deleted file";

// create a directory
if (ftp_mkdir( $conn, 'Vacation' )) {
    print "Created new directory";

// now let's try to set permissions for a file
if (ftp_chmod( $conn, 0755, 'download.pl') !== false) {
    print "Successfully made program executable";

// finally, close the connection
ftp_close( $conn );

I hope the article was helpful and will enable you to FTP enable your PHP scripts.

All times are GMT +5.5. The time now is 02:11.