Transfer Files Using FTP in PHP

pradeep's Avatar author of Transfer Files Using FTP in PHP
This is an article on Transfer Files Using FTP in PHP 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 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, '') !== 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.