Treehouse

Send Files via FTP Using PHP

By on  

Sending files to a server via FTP is an essential ability of any web developer or designer. Of course, we all use glossy FTP clients like WS_FTP and FireFTP, but what about FTP automation? You can use PHP to FTP files from one server to another. Let me show you how.

The PHP

$connection = ftp_connect($server);

$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);

if (!$connection || !$login) { die('Connection attempt failed!'); }

$upload = ftp_put($connection, $dest, $source, $mode);

if (!$upload) { echo 'FTP upload failed!'; }

ftp_close($connection); 

Obviously, the first task is to connect to the other server. Once the connection is created, you pass the login credentials. Once you're logged in, you can use the ftp_put() function to send the file. That's it!

What would you use this for? Well, you could set up a cron to create a database backup and send it to an offsite server.

ydkjs-5.png

Recent Features

  • 5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

Incredible Demos

  • Image Data URIs with PHP

    If you troll page markup like me, you've no doubt seen the use of data URI's within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves...

  • Facebook Sliders With Mootools and CSS

    One of the great parts of being a developer that uses Facebook is that I can get some great ideas for progressive website enhancement. Facebook incorporates many advanced JavaScript and AJAX features: photo loads by left and right arrow, dropdown menus, modal windows, and...

Discussion

  1. hey!, you forgot to put the source code !!!

    • mahadeva parsad

      hay i tried to connect to server using ftp from my local system but it coud’t connect to server.my code is correct but it not work please suggest me how to connect with how to pass parameters in details.I hope u help me…………….

  2. @Alex: It’s there.

  3. great script !!!!
    Thanks!!!!

  4. What about using the FTP wrappers instead? The resulting code should be shorter and more intuitive. You could do the following directly and be done with it:

    $upload = copy($source, ‘ftp://user:password@host/path/file’);
    if (!$upload) { echo ‘FTP upload failed!’; }

  5. Cool :)

  6. Jacob Molin

    $upload = copy($source,
    ‘ftp://user:password@host/path/file’);
    if (!$upload) { echo ‘FTP upload
    failed!’; }

    I think the way David Walsh do it is more secure.

    I don’t know but i think so ;)

  7. I’d say they’re both as insecure. The work done behind the scenes for this particular snippet is the same. If you needed better control (e.g. chmod), however, you would have to use the ftp extension. But most of the time it’s not needed.

  8. Yay, I didn’t even know there was FTP functions in PHP.

    Could be useful to backup stuff… if it was more secure. Also, I think the script run time is limited (to 30 seconds in my case) on lots of hosts.

  9. The 30 seconds time-limit can in most cases be changed using
    set_time_limit(x);.

    If changed, it allows an execution time longer (or shorter…) than the default 30 secs.

  10. Jacob Molin

    Yay, I didn’t even know there was FTP
    functions in PHP.

    Could be useful to backup stuff… if it
    was more secure. Also, I think the
    script run time is limited (to 30
    seconds in my case) on lots of hosts.

    Yes for MySQL BackUp i also use it together with a timer.

    But if i want to make a backup of other files on my ftp server i prefer cobian backup!
    Cobian
    In the start it was a professional programmer who made the program up to version 7 i think. Then he didn’t have time for it, and he published as opensource.
    Many other has then made the program up to version 9!

  11. great job =)

  12. Mike

    And if you want to see progress ?

  13. You can’t really see progress using PHP, that’d be more along the lines of Java or Perl. Well, truthfully, if you mess around with output buffering and the ftp nonblocking upload options, you can use ftp_nb_fput() or ftp_nb_put() along with ob_implicit_flush() to send out data via a while loop that updates the page. This can also be done via AJAX, if you flush your output buffer before uploading the file. At that point you can use an XMLHttpRequest to periodically (maybe every second) check on the file’s progress via another PHP file. I personally use Perl alongside the AJAX option though. If you do any of that though, watch out because you cannot force a header at that point, it all has to be done in the output. So it’d require multiple flushes of the output buffer.

  14. Diego

    I get two problems:

    the script run time is limited
    I can’t see progress

    I would like to use this way to upload big files, rather than “post” way.

    EDIT: to solve the run time troubble, you should write “set_time_limit(0)” at the begin of the script (I don’t know if this could be insecure)

  15. Abhinav joshi

    Cool :)

  16. Got more ideas, but can we restrict user to send only .doc file

  17. trink

    Yes.
    Before $upload = ftp_put($connection, $dest, $source, $mode); put this:
    if(substr($dest,-4) != ‘.doc’) die(“You may only upload .doc files.”);
    Obviously the die() can be replaced with your own error handler, just ensure that it halts the script, or just put the rest in an else block.

  18. i did as you said but then i found this “Warning: ftp_put() [function.ftp-put]: Opening data channel for file transfer. in *“. can you explain why ?

    • Look at VINOTH’s post. You need to set:

      ftp_pasv($connection, true);

      once logged.

      Worked for me

  19. Disha Vaghela

    Hey David…its really helpful ! thnx a lot !!!

  20. blackbird

    @david: explain me below code and which are needed to replace with actual value.

    $upload = ftp_put($connection, $dest, $source, $mode);

    eg: $dest=..
    $source=..
    $mode=…

  21. Thanks forever web pages..

  22. tushar

    cool script
    q :-
    i want to get email id from any page if exist?
    how i do it ?
    help me

  23. i want to get email id from any page if exist?
    how i do it ?

  24. Nice article and insight. Good to have bumped onto your blog and met you.

  25. goood insight what is want to get mail as attactment

  26. murthy

    GOOOOD one i like it

  27. vinoth

    thank you guys!!!!!!!!!!

    i got error on this code. :(

    after spending little time, i got the solution.

    ftp_pasv($connection, true); // to turns on the passive mode

    works!

  28. this snippet saved my pain in uploading files remotely. im planning to make a central network for photos uploaded using a script on my “main” server.

  29. The code is incomplete, at best, if the code included a few comments, or if it was written in full, alot of counfusion could be avoided…

  30. Ujjawal

    can u give me complete source code of uploading bigger files like 50-100 mb’s ??

    • Retrobot

      I would also love to know this, any ideas?

  31. This Code is not working please tell me the procedure how it will work.
    Thanks in advance.

  32. great script, I was looking for a similar one for one of my project. Thanks David.

  33. Hi,

    I tried many times, But, I failed. I do not know why. I always receive Warning: ftp_put(): Could not create file. message. Anyone have any idea?

    Thanks

  34. vadiraj

    hey anybody will this code run irrespective of the system…what should be program running at client side….

  35. Thanks! It worked to upload backup files for me.

  36. $connection = ftp_connect(“xyz.com”);
    $login = ftp_login($connection, “your_xyz_ftp_username”, “your_xyz_ftp_password”);

    if (!$connection)
    {
    die(‘Connection attempt failed!’);
    }
    else{
    echo “connection passed”;
    }
    if (!$login)
    {
    die(‘Login attempt failed!’);
    }
    else{
    echo “login passed”;
    }
    ftp_pasv($connection, true);

    // $upload = ftp_put($connection, $dest, $source, $mode);

    $upload = ftp_put($connection, “www/recipe_image/adv_banner.jpg”, “adv_banner.jpg”, FTP_BINARY);

    if (!$upload) { echo ‘FTP upload failed!’; } else {echo “ftp upload passed”;}

    ftp_close($connection);


  37. // set_time_limit(0);
    $connection = ftp_connect("easycms.in");
    $login = ftp_login($connection, "admin@easycms.in", "hl0809@");
    if (!$connection)
    {
    die('Connection attempt failed!');
    }
    else{
    echo "connection passed";
    }
    if (!$login)
    {
    die('Login attempt failed!');
    }
    else{
    echo "login passed";
    }
    ftp_pasv($connection, true);

    $source = "adv_banner.jpg";
    $dest = "recipe_image/adv_banner.jpg";

    //$x = substr($dest,-4);
    // echo $x;

    if((substr($dest,-4) == ".jpg") || (substr($dest,-4) == ".png") )
    {
    //no problems;
    }
    else {
    die('You may only upload jpg or png files.');
    }

    $upload = ftp_put($connection, $dest, $source, FTP_BINARY);
    if (!$upload) { echo 'FTP upload failed!'; } else {echo "ftp upload passed";}

    ftp_close($connection);

    ?>

  38. Zee

    Hi , i used that code and transferred the file successfully to a ftp server i created. but if i try and transfer it to one of the award space servers it doesn’t work.

    Thanks!

    //Code to transfer the file
    $upload = ftp_put($connection, “test.” . $fileParts ,$source , FTP_BINARY);
    if (!$upload) { echo ‘FTP upload failed! ‘; }

  39. Jan Bakalar

    Nice scripts!

    Now how would you do it via PHP that you would not only upload a backup of a website to an FTP server, but also deleted the oldest backups (.let’s say zip files) so that there is only a certain amount of them (i.e. 10)?

    Thx for your help,
    Jan

  40. Ghostofwar

    Hi,
    I’m a php newbie…
    I’m having problems deleting and uploading files onto ftp site. The following is the php process file i’ve adopted..

  41. Ghostofwar

    document.location=’IMAGE_EDIT.php?error=2&type=’

    <?php
    }

    $IMAGEwidth = 1035;
    $IMAGEheight = 450;

    list($width, $height) = getimagesize($IMAGE);

    if ($width $IMAGEwidth or $height $IMAGEheight)
    {
    ?>

    document.location=’IMAGE_EDIT.php?error=1&type=’

    document.location=’upload_error.php’

    <?php
    }
    else {
    //echo "Connected to $host, for user $ftp_user_name”;
    //echo “Host IP is $hostip”;

    // delete a file
    $delete = ftp_delete($conn_id, $deletefile);
    if (!$delete)
    {
    ?>

    document.location=’IMAGE_EDIT.php?error=3&type=’

    document.location=’IMAGE_EDIT.php?error=3&type=’

    document.location = “IMAGE_COMPLETE.php?type=”;

  42. Ghostofwar

    <

    document.location=’IMAGE_EDIT.php?error=2&type=’

    <?php
    }

    $IMAGEwidth = 1035;
    $IMAGEheight = 450;

    list($width, $height) = getimagesize($IMAGE);

    if ($width $IMAGEwidth or $height $IMAGEheight)
    {
    ?>

    document.location=’IMAGE_EDIT.php?error=1&type=’

    document.location=’upload_error.php’

    <?php
    }
    else {
    //echo "Connected to $host, for user $ftp_user_name”;
    //echo “Host IP is $hostip”;

    // delete a file
    $delete = ftp_delete($conn_id, $deletefile);
    if (!$delete)
    {
    ?>

    document.location=’IMAGE_EDIT.php?error=3&type=’

    document.location=’IMAGE_EDIT.php?error=3&type=’

    document.location = “IMAGE_COMPLETE.php?type=”;

    >

  43. ghostofwar

    apologies…
    couldn’t get the whole file copied. help please…
    thanks!

  44. [...] ftp_close($connection);  http://davidwalsh.name/send-files-ftp-php Rispondi [...]

  45. Riken

    i have used this code it working fine.. but when i have test it with 500 files.. webpage is crashed.. it will upload some files but after some time it will crahsed.

    Thanks For Help…

  46. kumutha

    I want to make a ftp connection and to run a php file present on a remote server. uploading and downloading of files to remote server works for me perfectly. But i didnt find any solution for executing file. plz give a solution for dis issue.. thanks in advance..

  47. Unhelpful

    // What is $mode? No explanation given?
    // What is $dest? Is that a location? Or is that a remote file name?
    // If users have to go over to PHP.net to figure out what you’re talking about, it’s not much of a tut.
    // Thanks for trying.

    $connection = ftp_connect($server);

    $login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);

    if (!$connection || !$login) { die(‘Connection attempt failed!’); }

    $upload = ftp_put($connection, $dest, $source, $mode);

    if (!$upload) { echo ‘FTP upload failed!’; }

    ftp_close($connection);

  48. [...] [...]

  49. Kalabaw

    It Works!

  50. Even

    Hi! Guys..

    Please help me……
    I got a problem, and I can not find the way to solve it…… T︿T

    I want to upload xml file to my server.
    (FileZilla Server on Windows 7, and firewall closed).

    I used FileZilla upload file succeed in client .
    But I try to using PHP ftp_put and copy both function, and both failed.
    The following is message from FileZilla Server….

    > Connected, sending welcome message...
    > USER superman
    > 331 Password required for superman
    > PASS ********
    > 230 Logged on
    > CWD /SendFiles
    > 250 CWD successful. "/SendFiles" is current directory.
    > TYPE A
    > 200 Type set to A
    > PORT 10,132,30,254,231,8
    > 200 Port command successful
    > STOR Test.xml
    > 150 Opening data channel for file transfer.
    > 425 Can't open data connection.
    > QUIT
    > 221 Goodbye
    > disconnected.
    
  51. Even

    I still can’t solve it.
    I was setted port 2100, it can’t working.
    I found it can working when port setting normal port (21).

    So I used aother way… make it safe in facade and upload successful.
    I open firewall and setting connect from given IP.

    I think it is a way accomplish what I want.

  52. A silly Question.
    suppose I made a code to upload a file with size of 20mb to server A to server B.
    now after accessing the my code via URL, and close the browser, would it still keep uploading in background??

  53. Amila Udana Kalinga

    Thanks Loïc Hoguin, Try this if you upload a zipped like bigger files and overwrite is needed

    array('overwrite' => true));	 
    $stream_context = stream_context_create($stream_options);
    
    if(!@copy($source,$ftp_path,$stream_context)){
    	$errors= error_get_last();
    	echo "error on copying: ".$errors['type'];
    	echo "\n".$errors['message'];
    } else {
    	echo "File copied to remote!";
    }
    
  54. I need to move all my website files to another server using php. how can i do that?

  55. Sanjeet Kumar

    Hi,

    I want to create one php file (suppose delete.php) which is able to delete some data (like xyz data added in header all php files.) from ftp.

    I have using Drupal 7.

    Please someone help me.

    Thanks Advance

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!