Upload File with FTP using PHP

FTP is one of the most useful tool or protocol for all web developers or designers. We can move files from one server to another with FTP tools very easily. PHP provides build in support for FTP protocol. That’s why we can work with FTP very easily using some FTP functions. In this post I’m going to show how to upload or put file to a server using PHP functions.



Connecting to FTP Server:
$con = ftp_connect($host, 21);

Login to FTP Server:
ftp_login($con, $username, $password);

Uploading File:
ftp_put($con, $remote_file, $local_file, FTP_ASCII);

Closing Connection:
ftp_close($con);

Bring All Together:
$host = "localhost";
$username = "username";
$password = "password";
$local_file = 'path/to/file.txt';
$remote_file = 'public_html/file.txt';

$con = ftp_connect($host, 21) or die("Could not connect to FTP server");
$log = ftp_login($con, $username, $password) or die("Fail to longin");
$upload = ftp_put($con, $remote_file, $local_file, FTP_ASCII);
if($upload) echo 'Success!';
ftp_close($con);

9 comments:

  1. hi...

    i want to ask,how to upload multiple file via ftp using php?I take a lot of time in searching it....there is answer that we can use "multiple" but i don't know how to do the looping process..
    Hope you can help me....

    ReplyDelete
    Replies
    1. Thanks for your query! I hope this code will help you...

      $files = array(
      'local/1.txt' => 'remote/1.txt',
      'local/2.txt' => 'remote/3.txt',
      'local/3.txt' => 'remote/3.txt');

      foreach($files as $local => $remote){
      $upload = ftp_put($con, $remote, $local, FTP_ASCII);
      }

      Delete
    2. Thanks for your code...but,i don't know how to implement it in my coding.Can you help me by giving full example of codes that include html and php part...

      Delete
    3. only PHP:

      http://pastebin.com/CC3xLG01

      Delete
    4. thanks...but i don't understand the array part which is:

      'path/to/local/file1.txt' => 'path/to/remote/file1.txt'

      is it i have to write the path for the file to upload?

      Delete
    5. sorry,but can you give more clearer explanation on the codes that you give since i have took a lot of time on think about this.

      Delete
    6. Only for you full and final! 100% working! tested ;)

      http://paste.laravel.com/192H

      Delete
    7. thanks for your code...but i still have problem where error like this "ftp_put() [function.ftp-put]: The parameter is incorrect."...What's wrong?
      And also my ftp account is not localhost and have its username and password...i thought that we have to use the $ftp_server,$ftp_user_name,$ftp_user_pass??

      Then,my upload directory is at Local Disk (C)...
      What i've to change for this code??help me...
      Sorry,for make you trouble...

      Delete

Go to top