DEV Community

Sanchita Paul
Sanchita Paul

Posted on

How to Upload Files via SFTP in Laravel

Secure File Transfer Protocol (SFTP) allows secure uploading of files between servers. In Laravel, the phpseclib/phpseclib package facilitates SFTP functionalities.

Prerequisites
Before proceeding, ensure:

Laravel is installed and configured.To upload a file via SFTP using Laravel, you can use the phpseclib/phpseclib package, which allows secure file transfers. First, ensure you have this package installed in your Laravel project:

composer require phpseclib/phpseclib
Enter fullscreen mode Exit fullscreen mode

Implementing SFTP Upload in a Route

use phpseclib\Net\SFTP;


Route::post('/upload-html-file', function () {
    $domain = 'your_domain';
    $username = 'your_username';
    $password = 'your_password';

    $sftp = new SFTP($domain);
    if (!$sftp->login($username, $password)) {
        return response()->json(['message' => 'SFTP connection failed'], 500);
    }

    $localFilePath = public_path('assets/web/theme/html/book_landing_page.html');
    $fileName = pathinfo($localFilePath, PATHINFO_BASENAME);
    $remoteFilePath = '/home/your_username/public_html/' . $fileName;
    if (!file_exists($localFilePath)) {
        return response()->json(['message' => 'Local file not found'], 404);
    }

    if ($sftp->put($remoteFilePath, file_get_contents($localFilePath))) {
        return response()->json(['message' => 'File uploaded successfully']);
    } else {
        return response()->json(['message' => 'File upload failed'], 500);
    }

});

Enter fullscreen mode Exit fullscreen mode

I just write this code on api.php as a testing purpose. Do not write code directly on route like this.

Replace $localFilePath with the path to your local HTML file.
Modify $remoteFilePath to define the remote server's desired location.

This code snippet establishes an SFTP connection using Laravel and uploads a specified local HTML file to a defined folder on the remote server.

Note: For production, it's recommended to manage sensitive credentials like usernames and passwords securely, possibly using environment variables.

Further Enhancements
For a production-ready solution:

Implement this logic within controllers and services.Securely store credentials using Laravel's environment variables.Communicate with this endpoint from your frontend to trigger file uploads as needed.Now you can securely transfer files using SFTP within your Laravel application!

*Hope it might help. Happy Coding *

Top comments (0)