PHP

Zip Folder SFTP dengan Menggunakan PHP

Adakalanya kita membutuhkan script untuk mendowload beberapa file menjadi satu file zip untuk mempermudah dalam melakukan download pada halaman website.

Berikut cara membuat script untuk proses pengabungan file dari SFTP menjadi satu file zip sebelum memulai pastikan library phpseclib ada di folder project website jika tidak silahkan download disini  :

 

<?php
    // set location phpseclib
  set_include_path(get_include_path().PATH_SEPARATOR.'./phpseclib0.3.0');

  include("Net/SFTP.php");

    // connection SFTP
    $sftp = new Net_SFTP('ip_address');
    if (!$sftp->login('user', 'password')) 
    {
        die("Cannot connect");
  }

    // Location directory
    $path = "url_address";
  $list = $sftp->nlist($path);

    // Check directory
    if ($list === false)
    {
        die("Error listing directory ".$path);
  }

    $file_name = "file_name.zip";
    $matches = preg_grep("/^$file_name.*/i", $list);
    // Check file
    if (count($matches) != 1)
    {
        die("No file or more than one file matches the pattern: ".implode(",", $matches));
  }

    $matches = array_values($matches);
    $filename = $matches[0];
    $filepath = $path."/".$filename;
    if (!$sftp->get($filepath, $filename))
    {
        die("Error downloading file ".$filepath);
    }
 
    $file = ($file_name);
    $filetype=filetype($file);
    $filename=basename($file);
    header ("Content-Type: ".$filetype);
    header ("Content-Length: ".filesize($file));
    header ("Content-Disposition: attachment; filename=".$filename);
    readfile($file);
    unlink($file_name);
?>

 

Selamat mencoba, terima kasih

Kenapa Perlu Zip Folder via SFTP?

Dalam pengelolaan server, seringkali kita perlu mengunduh folder atau direktori lengkap dari server remote. Namun, SFTP secara default hanya mendukung transfer file individual, bukan folder. Solusinya adalah meng-zip folder terlebih dahulu di server, kemudian mengunduh file zip tersebut melalui SFTP menggunakan PHP.

Menggunakan SSH2 Extension di PHP

PHP menyediakan extension SSH2 yang memungkinkan koneksi SFTP. Pastikan extension ini sudah terinstall:

<?php
// Koneksi ke server
$connection = ssh2_connect('hostname', 22);
ssh2_auth_password($connection, 'username', 'password');

// Membuka SFTP session
$sftp = ssh2_sftp($connection);

// Mengeksekusi perintah zip di server remote
$stream = ssh2_exec($connection, 'zip -r /tmp/folder.zip /path/to/folder');
stream_set_blocking($stream, true);
$output = stream_get_contents($stream);
fclose($stream);

// Mengunduh file zip
ssh2_scp_recv($connection, '/tmp/folder.zip', 'local_folder.zip');
?>

Contoh Lengkap dengan Error Handling

Berikut contoh yang lebih lengkap dengan penanganan error:

<?php
try {
    // Konfigurasi
    $host = 'server.example.com';
    $port = 22;
    $user = 'username';
    $pass = 'password';
    $remotePath = '/var/www/html/project';
    $localPath = 'backup/project.zip';
    
    // Koneksi
    $conn = ssh2_connect($host, $port);
    if (!$conn) throw new Exception('Gagal koneksi ke server');
    
    // Autentikasi
    if (!ssh2_auth_password($conn, $user, $pass)) {
        throw new Exception('Autentikasi gagal');
    }
    
    // Zip folder di server
    $cmd = "cd " . dirname($remotePath) . " && zip -r /tmp/backup.zip " . basename($remotePath);
    $stream = ssh2_exec($conn, $cmd);
    stream_set_blocking($stream, true);
    $output = stream_get_contents($stream);
    fclose($stream);
    
    // Download file zip
    if (!ssh2_scp_recv($conn, '/tmp/backup.zip', $localPath)) {
        throw new Exception('Gagal mengunduh file');
    }
    
    // Cleanup di server
    ssh2_exec($conn, 'rm /tmp/backup.zip');
    
    echo "Backup berhasil: $localPath";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

Tips dan Best Practices

  • Gunakan SSH key - Lebih aman dibanding password authentication
  • Batasi ukuran folder - Sebelum zip, cek ukuran folder untuk menghindari timeout
  • Validasi path - Selalu validasi path input untuk mencegah command injection
  • Gunakan ZipArchive - Alternatif lain, gunakan class ZipArchive PHP untuk zip lokal sebelum upload
  • Monitoring proses - Tambahkan logging untuk memantau proses backup yang berjalan

Kesimpulan

Meng-zip dan mengunduh folder melalui SFTP dengan PHP memudahkan proses backup dan migrasi data. Dengan error handling yang baik dan keamanan yang diperhatikan, proses ini dapat diotomasi untuk kebutuhan administrasi server.



0 Comments


Leave a Reply

Comments with links or spam keywords will be rejected.
Scroll to Top