How to connect and upload files on FTP using PHP

Here We’ll discuss about How to connect and upload files on FTP using PHP, If you are working on application where some files automatically generated on server and you want to move those files on your FTP server pragmatically then you can use following function to transfer files on FTP server using php, In other case If you are taking scheduled backup of your application and database and looking to move those backup files automatically on your backup FTP server then this code is also helpful.


How to Connect FTP using PHP

Using ftp_connect function you can easily connect your ftp server via PHP. Only need to pass your FTP hostname.

$ftpServer = "ftp.iamrohit.in";
$ftpConnID = ftp_connect($ftpServer) or die("Could not connect to $ftpServer");

How to Login FTP using PHP

After successful connection you need to login in your FTP server, With the help of ftp_login function you can loged in your FTP server by passing connection id, ftp username and ftp password.

$login = ftp_login($ftpConnID, $FtpUsername, $ftpPassword);

How to Transfer file on FTP using PHP

ftp_put will help you to transfer file on FTP

if (ftp_put($ftpConnID, "serverfile.txt", $file, FTP_ASCII))
  {
  echo "Successfully uploaded $file.";
  }
else
  {
  echo "Error uploading $file.";
  }

Using above function I have created simple PHP custom function to upload files on FTP.

function uploadFileFTP($ftpServer, $ftpUsername, $ftpPassword,  $remoteFile, $localFile){
    // connect to ftp server
    $ftpConnID = ftp_connect($ftpServer);
    // login to ftp
    if (@ftp_login($ftpConnID, $ftpUsername, $ftpPassword)){
        // successfully connected
    }else{
        // Error to log-in in ftp
        return false;
    }
    if(ftp_put(ftp_put($ftpConnID, $remoteFile, $localFile, FTP_ASCII) {
      echo "File uploaded successfully";
     } else {
      echo "Error to upload file on FTP server";
     }
    // close connection
    ftp_close($connection);
}

Call above function and pass required parameter and upload files on FTP server.

uploadFileFTP("ftp.iamrohit.in", "username", "password", "websitebackup/db/database.sql", "C:\\backup\database.sql");



Posted in: PHP

2 Replies to “How to connect and upload files on FTP using PHP”

  1. suddenly my cpanel database create the 1346 error
    that is does not accept null value for int type
    please any one help me
    

  2. Hi,
    Its working but when I try to upload .htaccess file it not works. So I upload with another name like file.htaccess then try to rename it but its not working. Any idea?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.