This tutorial will show you some PHP functions that can be used to work with FTP and doing different things :
- connect to FTP.
- list content (files and directories from FTP server)
- upload files to FTP.
I divided this tutorial into two parts to be easier to read and understand.
Using FTP inside of PHP is very useful for example if you make a PHP script that makes backups, you will need to store that backup on an external server. You can add the PHP script in cron and you are done. Let’s start :
1. For connecting to FTP you need three things: the host, the user and the password. First of all, you need to make the connection to the FTP server using ftp_connect(). This receives as an argument only the host or IP. After that using ftp_login() function you can login to the FTP. This function receives conn_id which is the id of the connexion returned by ftp_connect(); also the user and the password must be given. For closing the connection you can use ftp_close() which receives conn_id as parameter.
It’s easy to understand the code above so I will not explain it.
2. To list the files and directories from another directory you can use ftp_nlist(conn_id, dir).
As you can see from the example above, the result is an array which can be displayed easily in a FOR loop.
3. Uploading files – ftp_put(conn_id, destination, file, transfer_type) – this will return TRUE if file was uploaded succesfully or FALSE otherwise.
- conn_id – is the connection id.
- destination – the directory where the file will be uploaded.
- file – the name of the file.
- transfer_type – can be FTP_ASCII or FTP_BINARY.
That’s it for now! You can see the rest in Using FTP inside PHP – Part 2.