2011-09-14 287 views
6

Estoy tratando de descargar un archivo de un servidor sftp usando php pero no puedo encontrar la documentación correcta para descargar un archivo.¿Cómo descargar un archivo de SFTP usando PHP?

<?php 
$strServer = "pass.com"; 
$strServerPort = "22"; 
$strServerUsername = "admin"; 
$strServerPassword = "password"; 
$resConnection = ssh2_connect($strServer, $strServerPort); 
if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) { 
    $resSFTP = ssh2_sftp($resConnection); 
    echo "success"; 
} 
?> 

Una vez que tengo la conexión SFTP abierta, ¿qué debo hacer para descargar un archivo?

+1

Así que la pregunta es? –

+0

@Baszz leer el título. –

+1

@OZ_: Lo sé ... Lo edité de esa manera. –

Respuesta

5

Usando phpseclib, a pure PHP SFTP implementation:

<?php 
include('Net/SFTP.php'); 

$sftp = new Net_SFTP('www.domain.tld'); 
if (!$sftp->login('username', 'password')) { 
    exit('Login Failed'); 
} 

// outputs the contents of filename.remote to the screen 
echo $sftp->get('filename.remote'); 
?> 
3

Una vez que tenga su conexión SFTP abierta, se puede leer y escribir archivos utilizando funciones PHP estándar, tales como fopen, fread y fwrite. Solo necesita usar el manejador de recursos ssh2.sftp:// para abrir su archivo remoto.

Aquí es un ejemplo que va a escanear un directorio y descargar todos los archivos en la carpeta raíz:

// Assuming the SSH connection is already established: 
$resSFTP = ssh2_sftp($resConnection); 
$dirhandle = opendir("ssh2.sftp://$resSFTP/"); 
while ($entry = readdir($dirhandle)){ 
    $remotehandle = fopen("ssh2.sftp://$resSFTP/$entry", 'r'); 
    $localhandle = fopen("/tmp/$entry", 'w'); 
    while($chunk = fread($remotehandle, 8192)) { 
     fwrite($localhandle, $chunk); 
    } 
    fclose($remotehandle); 
    fclose($localhandle); 
} 
+0

A partir de PHP5.6, esto no funcionará y fallará silenciosamente:

 $remotehandle = fopen("ssh2.sftp://$resSFTP/$entry", 'r'); 
$ resSFTP se debe convertir explícitamente a int:
 $remotehandle = fopen('ssh2.sftp://' . intval($resSFTP) . '/$entry', 'r'); 

Cuestiones relacionadas