Download and Upload Files Through FTP in PHP

Download or Upload file to the server via FTP is an essential task for every web developers should know. There are many FTP clients are available for handling files on FTP server. You can also connect FTP server using PHP script and handle file operations.

PHP provides various functions to handle FTP server operations and there are many other library for the same. In this tutorial, we will show you how connect FTP server in PHP and we will also take some examples to perform download and upload file to FTP server.

FTP Server Connection in PHP

FTP works just like databases. Which means before performing any operations we need to connect it using credentials and server address. The ftp_connect() function is used to connect PHP and FTP server.

Once we established connection with FTP server then we can perform login attempt using ftp_open() function by providing valid username and password. Let's take an example to connect and login FTP server using PHP.

Here, first of all we have defined server and credentials into variables then try to connect with FTP server using ftp_connect() function. If it connect to FTP then it will try to login using our credentials and print message as response. It will print output something like below.

While connecting we can also specify port like below syntax :

Upload File to FTP Server Using PHP

After login, we can perform operations like upload, download and delete. We will use ftp_put() function to upload file on the server. The ftp_put() function requires few parameters like ftp object, remote file name, local file name and mode.

Both remote and local path need to be full path and mode must be FTP_ASCII or FTP_BINARY. Let's take example for uploading file to FTP server.

In above example, first of all we will connect and try to login using given credentials. Then it will try to upload file using ftp_put() function and print message as per response.

There are some other function like ftp_pasv() or ftp_fput() which can be used to upload file to FTP server.

Download File from the FTP Server Using PHP

To download file, we can use ftp_get() function. It requires same parameter as upload function but in a different order. Let's understand more using example.

Delete File From FTP server

To delete file, you can use ftp_delete() function. It just requires two parameter first one is FTP connection object and second one is file name which you want to delete.

Conclusion

In this article, we have learned about FTP connection, log in to FTP server and perform operations like upload, download and delete files using PHP. But there are many other FTP operations and functions that we can use as per our requirements like executing some commands, getting file size or change file permissions.


Share your thoughts

Ask anything about this examples