Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : FTP Functions : ftp_put


Uploads a file to the FTP server (PHP 4, PHP 5)
bool ftp_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos] )

Example 741. ftp_put() example

= 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
"successfully uploaded $file\n";
} else {
"There was a problem while uploading $file\n";

// close the connection

Code Examples / Notes » ftp_put


When using versions of PHP below 4.04b4, the ftp_put command doesn't work on NT/IIS4. Most of the other functions will work, but there was a bug while trying to send upstream data to an IIS webserver.


victor at nobel dot com dot br wrote that
the correct dirpath format excluded "/home/USER/" from the public path, but for my server, i had to use it in order to get my scripts to work.
it may be obvious to most but I'm positing that you cannot use the $_SERVER['DOCUMENT_ROOT'] path since FTP starts at your top-level and therefore bypasses (or just plain doesn't recognize) most of the virtual server pathing.


This solution to a common problem is implied elsewhere, but I thought it might be useful to put it all in one place (since I spent hours piecing it together!)
Sometimes a web host will open PHP sessions with a user of 'nobody'. Files created by this user may not have the correct permissions to allow  management of those files by the actual owner of the site.  The following script allows the actual owner to open access to a directory so that 'nobody' can create a file using fopen(). Then using the handle created by 'nobody', the ftp_fput() command saves the file with the correct owner.  The file 'nobody' created is discarded.
$connection = ftp_connect($ftpServer);
ftp_login($connection, $ftpUser, $ftpPass);
ftp_chdir($connection, $ftpDir);
// open the directory so that 'nobody' can create a temporary file
ftp_site($cn, "CHMOD 777 $ftpDir");
@unlink($new); // just in case
fputs($handle,"a bunch of stuff...");
fclose($handle); // have to rewind
ftp_fput($connection, "finalFile", $handle, FTP_ASCII);
// remove open access to the directory
ftp_site($connection, "CHMOD 755 $ftpDir")


This is an extremely trivial thing but one that had me stumped forever (well, until I decided to check the error logs and see the error). I had a large file (mysql backup of a huge forum) that was only partially being uploaded to a remote backup server. Couldn't figure out why, until I realized that the max execution time was being hit since it was taking longer than 30 seconds to upload this file.
rest of the code here....
That did the trick. It's one of those dumb, trivial things, and if you're having trouble like I, it may be something you overlooked.


The following is a fully tested function (based on a previous note) that recursively puts files from a source directory to a destination directory. See for more information.
NOTE: use full path name for the destination directory and the destination directory must already exist
function ftp_putAll($conn_id, $src_dir, $dst_dir) {
   $d = dir($src_dir);
   while($file = $d->read()) { // do this for each file in the directory
       if ($file != "." && $file != "..") { // to prevent an infinite loop
           if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
               if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
                   ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
               ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
           } else {
               $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files


If you want to copy a whole directory tree (with subdiretories),
this function (ftp_copy) might be usefull. Tested with
php 4.2.2 and a Linux OS.
$conn_id = ftp_connect("server_adress");
$src_dir = "/from";
$dst_dir = "/to";
ftp_copy($src_dir, $dst_dir);
Function: ftp_copy()
function ftp_copy($src_dir, $dst_dir) {
global $conn_id;
$d = dir($src_dir);
while($file = $d->read()) {
if ($file != "." && $file != "..") {
if (is_dir($src_dir."/".$file)) {
if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
ftp_mkdir($conn_id, $dst_dir."/".$file);
ftp_copy($src_dir."/".$file, $dst_dir."/".$file);
else {
$upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY);


if you examine the first user submitted function, ftp_putAll, it will work only if you extract this line and its matching bracket.
if (!@ftp_chdir($conn_id, $dst_dir."/".$file))
The function will have changed into that directory before having uploaded files to it.  This alters your upload path and the system will try to upload into an essentially non-existent directory (duped at the end).
Hope this helps some of you.

koen dot depoorter

If you are having timeouts uploading a file, even very small files, you might have a look at ftp_pasv()
And don't forget to do it after your ftp_login();

rpl oye

I'm on IIS, and using freeftpd 1.0
and i don't have accesss to php.ini, and in a shared hosting environment...
the script is like this...
<div align="left"><pre><?
$ftp_server = /*"localhost";*/"*****";
$remote_file = rand()."_".stripslashes( removebadstring( basename($_POST['f_hidden'])));
// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

//ftp_pasv($conn_id, true); //you can comment or uncomment it if you using firewall
// echo "ftp pasv is on";

echo "login result : ".$login_result."\n";
echo "local file ".$localfile."\n";
echo "remote file ".$remote_file."\n";

echo "Current directory is now: " . ftp_pwd($conn_id) . "\n";
// change directory if needed,

if (ftp_chdir($conn_id, "files")) {
  echo "Current directory is now: " . ftp_pwd($conn_id) . "\n";
} else echo "can't change dir";

$contents = ftp_nlist($conn_id, ".");
// output $contents

if (ftp_put(
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";

// close the connection
function removebadstring($word){
//$string = "%,^,#,'";
$stringA = array("%5E","^","^^","#","'","%");
$words = str_replace($stringA,"",$word);
return $words;
// this js function will fill f_hidden form value with full path of a local file
function changehidden(){
<div id="container">
 <div id="sidebar1">
 <!-- end #sidebar1 --></div>
 <div id="mainContent">
   <h1> Main Content </h1>
   <form action="<?=$_SERVER['PHP_SELF']?>" enctype="application/x-www-form-urlencoded" method="post" name="uploadForm" id="uploadForm">
     <input type="file" name="f" id="f" onChange="changehidden()" />
     <input type="hidden" name="f_hidden" value="" />      
     <input type="submit" name="button" id="button" value="Submit" />
     <input type="hidden" name="MAX_FILE_SIZE" value="1073741824" />
this script is working well on localhost ( in a local environment (apache 2, php 4.4 and filezilla ftp server))
but after i upload it in production environment (iis,php4.4, freeftpd 1.0) this script will produce "There was a problem while uploading" which is because of ftp_put command..
please help me, where the hell is wrong with ftp_put command , because in apache and filezilla ftpd is fine..
nb: i'm commenting pasv command because there is no time out error while executing this script


I'm copying fairly large backup files from server to server. ftp_put was running fine for awhile until it occasionally began reporting errors.
When I set TRUE as the value for the ftp_pasv () (after login), ftp_put started working again.


I spent some time debugging a silly problem:
In php >= 5, ftp_put() will apparently rewind to the start of the file regardless of the state you left it in before sending it to the $host.
I found this out because I wasn't closing the file handle before using ftp_put(). Since I had just written to the file, the file pointer must have been located at the *bottom*.
I was sending a 0-byte file on php 4.2.2., but worked fine on php 5.
So, just a heads up, don't forget to close those filehandles. Even though I was using the filename as the argument for ftp_put, it still needs to be closed.
I did not call rewind on the file handle, just fclose($file_h).


I had a little trouble getting the ftp_put to work, because of that particular server.  All variables and data parsed from the previous web form had to be retreived using $_POST, $_GET or $_FILES.
If you don't know what you sent use phpinfo(); to display what the server thinks about your data.
so...when sending files using a form and PHP, make sure that all the data (text files etc...) are retreived with $_POST, and files (smiley.png,, etc...) are retreived with $_FILES.
here's what your start of a results.php file might look like:
  $myName = $_POST['name']; //This will copy the text into a variable
  $myFile = $_FILES['file_name']; // This will make an array out of the file information that was stored.
Now when it comes to transmitting that information...
       $destination_path = "src/bin/";
//where you want to throw the file on the webserver (relative to your login dir)
$destination_file = $destination_path."img.jpg";
//This will create a full path with the file on the end for you to  use, I like splitting the variables like this in case I need to use on on their own or if I'm dynamically creating new folders.
       $file = $myFile['tmp_name'];
//Converts the array into a new string containing the path name on the server where your file is.
$upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);// upload the file
if (!$upload) {// check upload status
echo "FTP upload of $destination_file has failed!";
} else {
echo "Uploaded $file to $conn_id as $destination_file";
hope this is usefull ^_^


Here is a fix for the function from lucas at rufy dot com below that will recursively put files from a source directory to a destination directory.  As written below, it won't put a file in a directory that already exists, because the the destination is altered.  So here is the corrected function that will allow it to work:
function ftp_putAll($conn_id, $src_dir, $dst_dir) {
  $d = dir($src_dir);
  while($file = $d->read()) { // do this for each file in the directory
      if ($file != "." && $file != "..") { // to prevent an infinite loop
          if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
              if (!@ftp_nlist($conn_id, $dst_dir."/".$file)) {
                  ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
              ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
          } else {
              $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files

darian lassan

ftp_put() overwrites existing files.
Again: trivial but not mentioned here.

tom pittlik

ftp_put() can display confusing warning messages as it returns one line of the remote server's response which may be multi lined.
If you're transferring large amounts of files note that some file systems only support up to 2000 files per directory. This had me stumped for a while.


If you wanna upload files from your harddisk by a form to a specified ftp this sample can help you...
First of all create the form:
<body marginwidth=4 marginheight=4 topmargin=4 leftmargin=4 bgcolor=white vlink="#0000ff" link="#0000ff">
<form name="Attachments"  method=POST action="sendimage.php" enctype="multipart/form-data">
<input type=hidden name=box value="">
<td nowrap width="1%">&nbsp;&nbsp;<b>Image:</b></td>
<td colspan=2>
<input type=file name=source_file size=20>
<input type=submit name=btnSubmit value=Submit size=20 style="border: 1px solid #0000FF"></form>
The critical point in this form is the usage of  enctype="multipart/form-data"
If you don't use this part your upload operations won't work.
Then u must create sendimage.php as follows:
   $conn_id = ftp_connect($ftp_server);
   // login with username and password
   $login_result = ftp_login($conn_id, $user, $passwd);
// check connection
  if ((!$conn_id) || (!$login_result)) {
       echo "FTP connection has failed!";
       echo "Attempted to connect to $ftp_server for user $ftp_user_name";
   } else {
       echo "
Connected to $ftp_server, for user $user
//directorylike /
 ftp_chdir($conn_id, "");
 ftp_chdir($conn_id, "compimages");
echo ("
print $destination_file;
echo ("
// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
       echo "FTP upload has failed!";
   } else {
       echo "Uploaded $source_file to $ftp_server as $destination_file";
// close the FTP stream
In this example code $source_file is the path of the file in your disk, and destination file is the name of the uploaded file in ftpserver.
In this code I use ftp_chdir to give the path of the
uploaded file within ftpserver..
For your questions about all categories of PHP my
c u...

Change Language

Follow Navioo On Twitter
eXTReMe Tracker