downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

ftp_alloc> <fbsql_warnings
[edit] Last updated: Mon, 01 Nov 2010

view this page in

XLIII. Funciones FTP

Introducción

Las funciones en esta extensión implementan acceso de cliente a servidores de archivos que entiendan el Protocolo de Transferencia de Archivos (FTP, por sus siglas en Inglés), tal y como se define en http://www.faqs.org/rfcs/rfc959. Esta extensión tiene como propósito el acceso detallado a un servidor FTP, brindando un amplio rango de control al script que se encuentre ejecutando. Si sólo desea leer desde un archivo o escribir sobre un archivo en un servidor FTP, considere el uso de la envoltura ftp:// con las funciones del sistema de archivos, medio que provee una interfaz más simple e intuitiva.

Requisitos

No se necesitan bibliotecas externas para construir esta extensión

Instalación

Para usar las funciones FTP con su configuración PHP, debe agregar la opción --enable-ftp cuando instale PHP 4 o versiones posteriores, o --with-ftp cuando use PHP 3.

La versión para Windows de PHP tiene soporte nativo para esta extensión. No se necesita cargar ninguna extensión adicional para usar estas funciones.

Configuración en tiempo de ejecución

Esta extensión no tiene directivas de configuración en php.ini.

Tipos de recursos

Esta extensión usa un tipo de recurso, que es el identificador de enlace de la conexión FTP devuelto por ftp_connect() o ftp_ssl_connect().

Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles solamente cuando la extensión ha sido o bien compilada dentro de PHP o grabada dinámicamente en tiempo de ejecución.

FTP_ASCII (integer)

FTP_TEXT (integer)

FTP_BINARY (integer)

FTP_IMAGE (integer)

FTP_TIMEOUT_SEC (integer)

Vea ftp_set_option() para más información.

Las siguientes constantes fueron introducidas en PHP 4.3.0.

FTP_AUTOSEEK (integer)

Vea ftp_set_option() para más información.

FTP_AUTORESUME (integer)

Determinar automáticamente la posición de continuación y la posición de comienzo para peticiones GET y PUT (funciona únicamente si FTP_AUTOSEEK está habilitado)

FTP_FAILED (integer)

La transferencia asincrónica ha fallado

FTP_FINISHED (integer)

La transferencia asincrónica ha terminado

FTP_MOREDATA (integer)

La transferencia asincrónica está aun activa

Ejemplos

Ejemplo 1. Ejemplo de FTP

<?php
// establecer una conexion basica
$id_con = ftp_connect($servidor_ftp);

// inicio de sesion con nombre de usuario y contrasenya
$resultado_login = ftp_login($id_con, $nombre_usuario_ftp, $contrasenya_ftp);

// chequear la conexion
if ((!$id_con) || (!$resultado_login)) {
        echo
"&iexcl;La conexi&oacute;n FTP ha fallado!";
        echo
"Se ha intentado la conexion con $servidor_ftp para el " .
            
"usuario $nombre_usuario_ftp";
        exit;
    } else {
        echo
"Conectado con $servidor_ftp, para el usuario $nombre_usuario_ftp";
    }

// cargar el archivo
$carga = ftp_put($id_con, $archivo_destino, $archivo_fuente, FTP_BINARY);

// chequear el status de la carga
if (!$carga) {
        echo
"&iexcl;La carga FTP ha fallado!";
    } else {
        echo
"Se ha cargado $archivo_fuente a $servidor_ftp como $archivo_destino";
    }

// cierra la secuencia FTP
ftp_close($id_con);
?>

Tabla de contenidos
ftp_alloc -- Reserva espacio para que un archivo sea cargado
ftp_cdup -- Cambia al directorio padre
ftp_chdir -- Cambia el directorio actual en un servidor FTP
ftp_chmod -- Establecer permisos en un archivo via FTP
ftp_close -- Cierra una conexión FTP
ftp_connect -- Abre una conexión FTP
ftp_delete -- Elimina un archivo en el servidor FTP
ftp_exec -- Solicita la ejecución de un programa en el servidor FTP
ftp_fget -- Descarga un archivo desde el servidor FTP y lo guarda en un archivo abierto
ftp_fput -- Carga un archivo abierto al servidor FTP
ftp_get_option -- Recupera varios comportamientos de tiempo de ejecución de la secuencia FTP actual
ftp_get -- Descarga un archivo desde el servidor FTP
ftp_login -- Inicia sesión en una conexión FTP
ftp_mdtm -- Devuelve el tiempo de la última modificación del archivo dado
ftp_mkdir -- Crea un directorio
ftp_nb_continue -- Continúa recuperando/enviando un archivo (modo no-bloqueo)
ftp_nb_fget -- Recupera un archivo desde el servidor FTP y lo escribe sobre un archivo abierto (modo no-bloqueo)
ftp_nb_fput -- Almacena un archivo desde un archivo abierto en el servidor FTP (modo no-bloqueo)
ftp_nb_get -- Recupera un archivo desde el servidor FTP y lo escribe sobre un archivo local (modo no-bloqueo)
ftp_nb_put -- Almacena un archivo en el servidor FTP (modo no-bloqueo)
ftp_nlist -- Devuelve una lista de archivos en el directorio dado
ftp_pasv -- Habilita o deshabilita el modo pasivo
ftp_put -- Carga un archivo al servidor FTP
ftp_pwd -- Devuelve el nombre del directorio actual
ftp_quit -- Alias of ftp_close()
ftp_raw -- Envía un comando arbitrario a un servidor FTP
ftp_rawlist -- Devuelve una lista detallada de archivos en el directorio dado
ftp_rename -- Renombra un archivo o un directorio en el servidor FTP
ftp_rmdir -- Elimina un directorio
ftp_set_option -- Establecer varias opciones FTP de tiempo de ejecución
ftp_site -- Envía un comando SITE al servidor
ftp_size -- Devuelve el tamaño del archivo dado
ftp_ssl_connect -- Abre una conexión segura SSL-FTP
ftp_systype -- Devuelve el identificador de tipo de sistema del servidor FTP remoto


ftp_alloc> <fbsql_warnings
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes Funciones FTP
spam at kacke dot de 28-Mar-2008 09:46
Here is a FTP-abstraction-class which supports the most commands.

Also it works on TLS, SSLv2 etc. by using stream_crypto_enable()

http://kacke.de/php_samples/source.php?f=ftp.cls.php

Many thanks to WEZ at this point after all the years :-)

Toppi
adityabhai at gmail dot com 10-Jan-2008 01:23
Here is the way you can do it:
First of all, copy paste the code in your php file.

Then run your script on the Server where you want to execute your code:

Fill in the Forms:
1) Server Path or IP like abc.com/1.2.3.4 only.
2) FTP Username
3) FTP Password
4) FTP Path, where you want to put the file, check the Folder permission first.

<?php
 
//-- SMTP Mail Function  By Aditya Bhatt
 
if(isset($_POST['SubmitFile'])){
     
$myFile = $_FILES['txt_file']; // This will make an array out of the file information that was stored.
     
$file = $myFile['tmp_name'];  //Converts the array into a new string containing the path name on the server where your file is.
 
     
$myFileName = basename($_FILES['txt_file']['name']); //Retrieve filename out of file path

     
$destination_file = $_REQUEST['filepath'].$myFileName;
     
#"/developers/uploadftp/aditya/".$myFileName;  //where you want to throw the file on the webserver (relative to your login dir)

      // connection settings
     
$ftp_server = trim($_REQUEST['serverip']);  //address of ftp server.
     
$ftp_user_name = trim($_REQUEST['username']); // Username
     
$ftp_user_pass = trim($_REQUEST['password']);   // Password

     
$conn_id = ftp_connect($ftp_server) or die("<span style='color:#FF0000'><h2>Couldn't connect to $ftp_server</h2></span>");        // set up basic connection
      #print_r($conn_id);
     
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<span style='color:#FF0000'><h2>You do not have access to this ftp server!</h2></span>");   // login with username and password, or give invalid user message
     
if ((!$conn_id) || (!$login_result)) {  // check connection
             // wont ever hit this, b/c of the die call on ftp_login
            
echo "<span style='color:#FF0000'><h2>FTP connection has failed! <br />";
             echo
"Attempted to connect to $ftp_server for user $ftp_user_name</h2></span>";
             exit;
         } else {
        
//    echo "Connected to $ftp_server, for user $ftp_user_name <br />";
     
}

     
$upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);  // upload the file
     
if (!$upload) {  // check upload status
        
echo "<span style='color:#FF0000'><h2>FTP upload of $myFileName has failed!</h2></span> <br />";
      } else {
         echo
"<span style='color:#339900'><h2>Uploading $myFileName Completed Successfully!</h2></span><br /><br />";
      }

     
ftp_close($conn_id); // close the FTP stream
 
}
?>

<html>
  <head></head>
  <body>
        <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
            Server IP Address: <input name="serverip" type="text" id="serverip" size="15" value=""/><br>
            Server Username: <input name="username" type="text" id="username" size="15" value=""/><br>
            Server Password: <input name="password" type="text" id="password" size="15" value=""/><br>
            Server File Path: <input name="filepath" type="text" id="filepath" size="35" value=""/><br>
            Please choose a file: <input name="txt_file" type="file" id="txt_file" tabindex="1" size="35" onChange="txt_fileName.value=txt_file.value" /><br><br>
            <input name="txt_fileName" type="hidden" id="txt_fileName" tabindex="99" size="1" />

            <input type="submit" name="SubmitFile" value="Upload File" accesskey="ENTER" tabindex="2" />
      </form>
  </body>
</html>

Enjoy..
dot a dot@dot dot com 17-Sep-2007 08:49
This took me a few hours to work out. It is based on the code below I've just added a string replace to convert pathname given by Windows to Unix pathname. Hope it saves somebody some time. Enjoy! (Also, delete file function is included:))

<?php   
$myFile
= $_FILES['file']; // This will make an array out of the file information that was stored.
   
$file = $myFile['tmp_name'];  //Converts the array into a new string containing the path name on the server where your file is.
   
$myFileName = $_POST['MyFile']; //Retrieve file path and file name   
   
$myfile_replace = str_replace('\\', '/', $myFileName);    //convert path for use with unix
   
$myfile = basename($myfile_replace);    //extract file name from path
   
$destination_file = "/".$myfile//where you want to throw the file on the webserver (relative to your login dir)
    // connection settings
   
$ftp_server = "127.0.0.1"//address of ftp server (leave out ftp://)
   
$ftp_user_name = ""; // Username
   
$ftp_user_pass = "";   // Password
   
$conn_id = ftp_connect($ftp_server);        // set up basic connection
    // login with username and password, or give invalid user message
   
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<h1>You do not have access to this ftp server!</h1>");
   
$upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);  // upload the file
   
if (!$upload) {  // check upload status
       
echo "<h2>FTP upload of $myFileName has failed!</h2> <br />";
    }
/*
    // try to delete $file
    if (ftp_delete($conn_id, $destination_file)) {
        echo "$destination_file has been deleted!\n";
    } else {
        echo "Could not delete $destination_file!\n";
    }
*/
ftp_close($conn_id); // close the FTP stream
}
?>
<form name="form" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
Please choose a file: <input type="file" name="file" accept="text/plain" onChange="MyFile.value=file.value">
<input name="MyFile" type="hidden" id="MyFile" tabindex="99" size="1" />
<input type="submit" name="submit" value="upload" style="vertical-align:middle"/><br/><br/>
</form>
chris at faktortel dot com dot au 08-Jul-2007 03:47
I had some major problems running ftp_connect from my Web Browser and not from the CLI from 1 server and yet from another Internal server I had no trouble at all. After a few hours I figured out this was because SELINUX was enabled on one server and DISABLED on the server that it worked on.

So in short, if you are having trouble with connecting in your Web Browser make sure you have HTTPD connect's enabled in it like so at the command prompt:

; Turns it on temporarily.
/usr/sbin/setsebool httpd_can_network_connect=1

; Turns it on Permenantly
/usr/sbin/setsebool -P httpd_can_network_connect=1

I hope this helps make someones life a little easier. :)
(I actually found this fix on the fopen manual page).
ras "at" fyn {dot} dk 26-Jan-2007 01:11
A function to get a remote file and return it's contents, instead of saving to a local file, was missing - here it is:

function ftp_fetch($ftp_stream, $remote_file) {
    ob_end_flush();
    ob_start();
    $out = fopen('php://output', 'w');
    if (!ftp_fget($ftp_stream, $out, $remote_file, FTP_ASCII)) die('Unable to get file: ' . $remote_file);
    fclose($out);
    $data = ob_get_clean();
    return $data;
}

It works the same as ftp_get(), but instead returns the contents of the remote file - for example:

$ftp = ftp_connect('my.server.com', 21, 60);
ftp_login($ftp, 'username', 'password');
$data = ftp_fetch($ftp, 'path/to/remote.file');
echo $data;

Note, I use it to fetch text-files from a server - if you need to fetch binary files, change FTP_ASCII to FTP_BINARY .. but most likely, getting files to memory is only useful for smaller files, e.g. plain text, xml, etc.
breese at pipetech dot tv 29-Dec-2006 09:02
I fixed the below upload script to work with Windows uploads (and updated some of the syntax). I also added a Javascript "progress indicator" for those of us who don't use PHP 5.2

<?php
if(isset($_POST['start_upload']) && $_FILES['txt_file']['name'] != ""){
    
   
$local_file = $_FILES['txt_file']['tmp_name']; // Defines Name of Local File to be Uploaded

   
$destination_file = "/".basename($_FILES['txt_file']['name']);  // Path for File Upload (relative to your login dir)

    // Global Connection Settings
   
$ftp_server = "127.0.0.1";      // FTP Server Address (exlucde ftp://)
   
$ftp_user_name = "username";     // FTP Server Username
   
$ftp_user_pass = "password";      // Password

    // Connect to FTP Server
   
$conn_id = ftp_connect($ftp_server);
   
// Login to FTP Server
   
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
   
   
// Verify Log In Status
   
if ((!$conn_id) || (!$login_result)) {
        echo
"FTP connection has failed! <br />";
        echo
"Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo
"Connected to $ftp_server, for user $ftp_user_name <br />";
    }

   
$upload = ftp_put($conn_id, $destination_file, $local_file, FTP_BINARY);  // Upload the File
   
    // Verify Upload Status
   
if (!$upload) {
        echo
"<h2>FTP upload of ".$_FILES['txt_file']['name']." has failed!</h2><br /><br />";
    } else {
        echo
"Success!<br />" . $_FILES['txt_file']['name'] . " has been uploaded to " . $ftp_server . $destination_file . "!<br /><br />";
    }

   
ftp_close($conn_id); // Close the FTP Connection
}
?>

<html>
    <head>
        <script type="text/javascript">
            window.onload = function() {
                document.getElementById("progress").style.visibility = "hidden";
                document.getElementById("prog_text").style.visibility = "hidden";
            }
           
            function dispProgress() {
                document.getElementById("progress").style.visibility = "visible";
                document.getElementById("prog_text").style.visibility = "visible";
            }
           
        </script>
       
    </head>
    <body>
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" enctype="multipart/form-data">
            Please choose a file: <input name="txt_file" type="file" size="35" />
            <input type="submit" name="start_upload" value="Upload File" onClick="dispProgress()" />
        </form>
       
        <!-- Link to progress file: see http://www.ajaxload.info/ for animated gifs -->
        <img id="progress" src="http://www.your.site/images/progress.gif" />
        <p id="prog_text" style="display:inline;"> Upload Started!</p>
       
    </body>
<html>
cgray at premierconsulting dot com (Chris Gray) 24-Oct-2006 08:58
After looking everywhere for a "FULLY WORKING" ftp uploader script, I finally came up with this, by using a lot of various one’s I found on the web. If you find a better way of doing something, please let me know. Thanks, and Enjoy

<?php
 
if(isset($_POST['SubmitFile'])){
     
$myFile = $_FILES['txt_file']; // This will make an array out of the file information that was stored.
     
$file = $myFile['tmp_name'];  //Converts the array into a new string containing the path name on the server where your file is.
 
     
$myFileName = basename($_POST['txt_fileName']); //Retrieve filename out of file path

     
$destination_file = "/".$myFileName//where you want to throw the file on the webserver (relative to your login dir)

      // connection settings
     
$ftp_server = "127.0.0.1"//address of ftp server.
     
$ftp_user_name = "Your UserName"; // Username
     
$ftp_user_pass = "Your Password";   // Password

     
$conn_id = ftp_connect($ftp_server);        // set up basic connection
     
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<h2>You do not have access to this ftp server!</h2>");   // login with username and password, or give invalid user message
     
if ((!$conn_id) || (!$login_result)) {  // check connection
             // wont ever hit this, b/c of the die call on ftp_login
            
echo "FTP connection has failed! <br />";
             echo
"Attempted to connect to $ftp_server for user $ftp_user_name";
             exit;
         } else {
        
//    echo "Connected to $ftp_server, for user $ftp_user_name <br />";
     
}

     
$upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);  // upload the file
     
if (!$upload) {  // check upload status
        
echo "<h2>FTP upload of $myFileName has failed!</h2> <br />";
      } else {
         echo
"Uploading $myFileName Complete!<br /><br />";
      }

     
ftp_close($conn_id); // close the FTP stream
 
}
?>

<html>
  <head>

  </head>
  <body>
        <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
            Please choose a file: <input name="txt_file" type="file" id="txt_file" tabindex="1" size="35" onChange="txt_fileName.value=txt_file.value" />
            <input name="txt_fileName" type="hidden" id="txt_fileName" tabindex="99" size="1" />

            <input type="submit" name="SubmitFile" value="Upload File" accesskey="ENTER" tabindex="2" />
      </form>
  </body>
<html>
nicklas at programmera dot nu 15-Aug-2006 02:56
I didn't quite like my FTP program since I had to make all the settings all over when i restarted the client, so I made this script for simple ftp uploading, its running as a CLI app.

<?php

   
//if STDIN isn't defined, define it
   
if (!defined("STDIN"))
    {
   
       
define("STDIN", fopen("php://stdin", "r"));
       
    }
   
    echo
"FTP file uploader\r\n\r\n";

    echo
"Server: ";

   
//trim() all the fgets cause it seams to add a \n
   
$server = trim(fgets(STDIN));
   
    echo
"Username: ";
   
   
$username = trim(fgets(STDIN));
   
    echo
"Password: ";
   
   
$password = trim(fgets(STDIN));
   
   
$connect = ftp_connect($server);
   
$login = ftp_login($connect, $username, $password);
   
    if ((!
$connect) || (!$login))
    {
   
        exit(
"Login failed.\r\n");
       
    }
   
    echo
"Connected\r\n";

    echo
"PASV (Y/Any key = Off): ";
   
    if(
trim(fgets(STDIN)) == "Y")
    {

       
//enable passive mode
       
ftp_pasv($connect, true);
   
            echo
"PASV: On\r\n";
       
    }
    else
    {
   
        echo
"PASV: Off\r\n";

    }

   
$showContent = ftp_nlist($connect, "");
   
    echo
"Listing Contents:\r\n";
       
       
var_dump($showContent);

    echo
"File to upload: ";
   
   
$file = trim(fgets(STDIN));
   
   
//escape the uploading process by typing "exit;"
   
if ($file == "exit;")
    {
   
        exit;
   
    }
   
   
//use "$file, $file" since the file shouldn't be renamed, also if its a binary file change the last argument to FTP_BINARY
   
$upload = ftp_put($connect, $file, $file, FTP_ASCII);
   
    if (!
$upload)
    {
   
        exit(
"Upload failed.\r\n");
       
    }
    else
    {
   
        echo
"The file \"" . $file . "\" was successfully uploaded. :)\r\nSize of \"" . $file . "\": " . filesize($file) / 1024 ."kb.\r\n";
        echo
"My work is done, bye.\r\n";
       
    }
   
   
ftp_close($connect);

?>
magic2lantern at mail dot ru 23-Dec-2005 08:19
This is a simple script writen by me which allows the user
run it in console and get tree from FTP Server.

<?php
$argv
= $_SERVER["argv"];
$argv = array_slice($argv,1);
if (
getenv("HTTP_HOST")) {exit("For bash execution only!");}
if ((empty(
$argv[0])) || (empty($argv[1]))) {exit("Usage: thisscript.php 10.0.0.10 /games/Arcade/
where 10.0.0.10 is the FTP Server and /games/Arcade is the start path on FTP\n"
);}

// connect to the ftp server
$connect_id = ftp_connect($argv[0]);
// login on the server
if ($connect_id) { $login_result = ftp_login($connect_id, 'anonymous', 'JustForFun'); }
// check connection
if ((!$connect_id) || (!$login_result)) {
   echo
"Unable to connect the remote FTP Server!\n";
   exit;
}
function
ftp_get_dir ($ftp_dir) {
global
$connect_id;
$ftp_contents = ftp_nlist ($connect_id, $ftp_dir);
    for (
$myCounter_for_server_elements = 0; !empty ($ftp_contents[$myCounter_for_server_elements]);
$myCounter_for_server_elements++)
    {
// get elements list in current dir
       
echo $argv[0] . $ftp_dir . $ftp_contents[$myCounter_for_server_elements] . "\n";
       
ftp_get_dir ($ftp_dir . $ftp_contents[$myCounter_for_server_elements] . '/');
    }
}
ftp_get_dir ($argv[1]);
// close connection
ftp_close($connect_id);
?>
leonardo at rol dot com dot ro 09-Aug-2005 06:51
Here is an example for downloading a remote ftp structure to local server, useful for migrating sites from one server to another, especially when you are upgrading ensim ;)

http://leonardo.rol.ro/ftpleech.txt
dickiedyce at uk dot com 07-May-2005 08:20
It may seem obvious to others, but it had me stumped for nearly an hour! If you can connect to an ftp site but some functions (list, put, get etc) don't work, then try using ftp_pasv and set passive mode on.

<?php

// setup $host and $file variables for your setup before here...

$hostip = gethostbyname($host);
$conn_id = ftp_connect($hostip);

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

// IMPORTANT!!! turn passive mode on
ftp_pasv ( $conn_id, true );

if ((!
$conn_id) || (!$login_result)) {
  echo
"FTP connection has failed!";
  echo
"Attempted to connect to $host for user $ftp_user_name";
  die;
} else {
  echo
"Connected to $host, for user $ftp_user_name<br>";
  echo
"Host IP is $hostip<br>";
 
 
// upload a file
 
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
    echo
"successfully uploaded $file<br>";
  } else {
    echo
"There was a problem while uploading $file<br>";
  }
   
 
// close the connection
 
ftp_close($conn_id);
}
?>
arjen at queek dot nl 15-Jul-2004 07:38
If you prefer a OO-approach to the FTP-functions, you can use this snippet of code (PHP5 only! and does add some overhead). It's just a "start-up", extend/improve as you wish...
You can pass all ftp_* functions to your object and stripping ftp_ of the function name. Plus, you don't have to pass the ftp-resource as the first argument.

For example:
<?php
ftp_delete
($ftp, $file);    // Where $ftp is your ftp-resource
?>

Can become:
<?php
$ftp
->delete($file);        // Where $ftp is your FTP-object
?>

Code:
<?php

class FTP {

    private
$ftp;
   
   
/* public Void __construct(): Constructor */
   
public function __construct($host, $port = 21, $timeout = 90) {
       
$this->ftp = ftp_connect($host, $port, $timeout);
    }
   
   
/* public Void __destruct(): Destructor */
   
public function __destruct() {
        @
ftp_close($this->ftp);
    }

   
/* public Mixed __call(): Re-route all function calls to the PHP-functions */
   
public function __call($function, $arguments) {
       
// Prepend the ftp resource to the arguments array
       
array_unshift($arguments, $this->ftp);
       
       
// Call the PHP function
       
return call_user_func_array('ftp_' . $function, $arguments);
    }
   
}

?>
Kristy Christie (kristy at isp7 dot net) 15-Jun-2004 11:50
Here's a little function that I created to recurse through a local directory and upload the entire contents to a remote FTP server.

In the example, I'm trying to copy the entire "iwm" directory located at /home/kristy/scripts/iwm to a remote server's /public_html/test/ via FTP.

The only trouble is that for the line "if (!ftp_chdir($ftpc,$ftproot.$srcrela))", which I use to check if the directory already exists on the remote server, spits out a warning about being unable to change to that directory if it doesn't exist.

But an error handler should take care of it.

My thanks to the person who posted the snippet on retrieving the list of files in a directory.

For the version of the script that echo's it's progress as it recurses & uploads, go to: http://pastebin.com/73784

<?php

// --------------------------------------------------------------------
// THE TRIGGER
// --------------------------------------------------------------------

    // set the various variables
   
$ftproot = "/public_html/test/";
   
$srcroot = "/home/kristy/scripts/";       
   
$srcrela = "iwm/";

   
// connect to the destination FTP & enter appropriate directories both locally and remotely
   
$ftpc = ftp_connect("ftp.mydomain.com");
   
$ftpr = ftp_login($ftpc,"username","password");

    if ((!
$ftpc) || (!$ftpr)) { echo "FTP connection not established!"; die(); }
    if (!
chdir($srcroot)) { echo "Could not enter local source root directory."; die(); }
    if (!
ftp_chdir($ftpc,$ftproot)) { echo "Could not enter FTP root directory."; die(); }

   
// start ftp'ing over the directory recursively
   
ftpRec ($srcrela);

   
// close the FTP connection
   
ftp_close($ftpc);

// --------------------------------------------------------------------
// THE ACTUAL FUNCTION
// --------------------------------------------------------------------
function ftpRec ($srcrela)
{
    global
$srcroot;
    global
$ftproot;
    global
$ftpc;
    global
$ftpr;
               
   
// enter the local directory to be recursed through
   
chdir($srcroot.$srcrela);
   
   
// check if the directory exists & change to it on the destination
   
if (!ftp_chdir($ftpc,$ftproot.$srcrela))
    {
       
// remote directory doesn't exist so create & enter it
          
ftp_mkdir    ($ftpc,$ftproot.$srcrela);
          
ftp_chdir    ($ftpc,$ftproot.$srcrela);
    }

    if (
$handle = opendir("."))
    {
       while (
false !== ($fil = readdir($handle)))
       {
           if (
$fil != "." && $fil != "..")   
           {
              
// check if it's a file or directory
              
if (!is_dir($fil))
               {   
                  
// it's a file so upload it
                  
ftp_put($ftpc, $ftproot.$srcrela.$fil, $fil, FTP_BINARY);
                }
                else
                {
                   
// it's a directory so recurse through it
                   
if ($fil == "templates")
                    {
                           
// I want the script to ignore any directories named "templates"
                            // and therefore, not recurse through them and upload their contents
                   
}
                    else
                    {
                       
ftpRec ($srcrela.$fil."/");
                       
chdir ("../");
                    }
                }
          }
      }
     
closedir($handle);
    }   
}
?>
postmaster at alishomepage dot com 24-Jan-2004 03:29
I have written an OpenSource ZIP2FTP interface, which actually takes a given ZIP file and decompresses it in the folder on an FTP server you specify...

Therefore it may be quite interesting for you people interested in FTP, its adress is http://zip2ftp.alishomepage.com ; those who directly want the source may visit http://zip2ftp.alishomepage.com/?do=getSource
Vikrant Korde <vakorde at hotmail dot com> 14-Nov-2003 05:35
<?

//If you want to move or replicate the folder hierarchy from your current server to another remote server. Then this will be helpful as this will browse the current server's directory and at the same time it will copy that file in the remote server in the same directory.

//This script will copy all the files from this directory and subdirectory to another remote server via FTP

function rec_copy ($source_path, $destination_path, $con)
{
   
ftp_mkdir($con, $destination_path);
   
ftp_site($con, 'CHMOD 0777 '.$destination_path);
   
ftp_chdir($con,$destination_path);

    if (
is_dir($source_path))
    {
       
chdir($source_path);
       
$handle=opendir('.');
        while ((
$file = readdir($handle))!==false)
        {
            if ((
$file != ".") && ($file != ".."))
            {
                if (
is_dir($file))
                {
                   
// here i am restricting the folder name 'propertyimages' from being copied to remote server. -- VK
                   
if($file != "propertyimages")
                    {
                       
rec_copy ($source_path."/".$file, $file, $con);
                       
chdir($source_path);
                       
ftp_cdup($con);
                    }
                }
                if (
is_file($file))
                {
                   
$fp = fopen($file,"r");
                   
// this will convert spaces to '_' so that it will not throw error.  -- VK
                   
ftp_fput ($con, str_replace(" ", "_", $file), $fp,FTP_BINARY);
                   
ftp_site($con, 'CHMOD 0755 '.str_replace(" ", "_", $file));
                }
            }
        }
       
closedir($handle);
    }
}

// make a FTP connection --VK
$con = ftp_connect("69.18.213.131",21);
$login_result = ftp_login($con,"username","password");   

// this is the root path for the remote server-- VK
$rootpath = "mainwebsite_html";   

// this is the physical path of the source directory. actually u can also use the relative path. -- VK
$sourcepath = realpath("../")."/resdesk";

// this directory name will only change the top most directory and not the inner one -- VK
$destination_dir_name = "resdesk_".$account_id."/";

rec_copy ($sourcepath, $destination_dir_name, $con);
if (
function_exists("ftp_close"))
{
   
ftp_close($con);
}
?>
postmaster at alishomepage dot com 24-Oct-2003 04:06
Here's another FTP interface over PHP (also uses MySQL)

http://myftp.alishomepage.com

PS: this script will ALSO allow you to download its source... So it becomes interesting for YOU PROGRAMMERS as well :D
NOSPAMkent at ioflux dot NOSPAM dot com 19-Sep-2002 05:05
I think what some other posts were trying to say which may need clarification is that in PHP 4.2.3, ftp_connect("myhost.com") was failing most of the time, except it would work like every few minutes.

The fix is that ftp_connect seems to have a bug resolving addresses. If you do:

$hostip = gethostbyname($host);
$conn_id = ftp_connect($hostip);

It seems to solve the problem.
(Other users referred to an ftpbuf() error... not sure what that is, but this should fix it.)
sven at cartell-network dot de 13-Feb-2002 11:27
connection to a ftp server across proxy

$ftp_server = "proxy"; f.e. 123.456.789.10
$ftp_user_name = "username@ftpserver"; f.e. exampleuk@www.example.uk
$ftp_user_pass = "password";

$conn_id = ftp_connect($ftp_server, 2121);
$login_result = ftp_login( $conn_id, $ftp_user_name, $ftp_user_pass );

 
show source | credits | sitemap | contact | advertising | mirror sites