About the procedure to introduce SFTP settings in Laravel and perform SFTP communication in the production environment or DEV environment

Aug 26, 2020 PHP Laravel sftp

#Introduction Since there was a matter to link the CSV file to the SFTP server, it will be a memo of the installation procedure at that time. I am writing an article to organize the work flow. In the processing environment, an environment containing PHP’s Laravel framework was prepared, so the flow is to add processing and settings for SFTP.

Please refer to this ArticleandSite for introduction.

#About the environment

#Introduction procedure

1. Install SFTP module

Go to the Laravel home directory and execute composer require to install the SFTP module.

composer require league/flysystem-sftp

If the installation result says “successfully” as shown below, it’s ok.


Using version ^1.0 for league/flysystem-sftp
./composer.json has been updated
(abridgement)
Package manifest generated successfully.

Also, the version of sftp is added to the requireofcomposer.json`.

{
   "require": {
       "league/flysystem-sftp": "^1.0"
   }
}

Another vendor/league/flysystem-sftp directory is created in the execution environment. I would like to be able to confirm this area.

2. Preparing sftp module

It is the same flow as Reference site, I wanted to separate the connection information for each environment, so I refer to it from .env.

2.1 Registration with Service Provider

Create a ServiceProvider class for sftp with the make:provider command.

# Command for generating service provider file
php artisan make:provider SftpServiceProvider
<?php

namespace App\Providers;

use Storage;
use League\Flysystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Sftp\SftpAdapter;

class SftpServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
      Storage::extend('sftp', function ($app, $config) {
        return new Filesystem(new SftpAdapter((
          'host' => $config['host'],
          'port' => $config['port'],
          'username' => $config['username'],
          'password' => $config['password'],
          'privateKey' => $config['privateKey'],
          'root' => $config['root'],
          'timeout' => $config['timeout'],
        ]));
      });
    }
    
}

2.2 Addition to File System

Add the disk settings for sftp to config/filesystem.php. At this time, the access settings of the production and DEV environment are referenced from .env.

If there is an undefined item, the value of the second argument of the env function is used. (The set value is set to a level that is null and no error occurs)

<?php

return [

   'disks' => [

        /* I think it also contains other disk settings, but I will omit it */

        'sftp' => [
            'driver' =>'sftp',
            'host' => env('SFTP_HOST','192.168.10.10'),
            'port' => env('SFTP_PORT',22),
            'username' => env('SFTP_USER','myName'),
            'password' => env('SFTP_PW','myPass'),
            'privateKey' => env('SFTP_PRIVATE_KEY','/home/myUser/.ssh/sftp_key.rsa'),
            'root' => env('SFTP_ROOT_DIR','/tmp'),
            'timeout' => 10,
          ],
    ],
];

Prepare the setting information in .env as follows.

SFTP_HOST=[domain or IP address of destination HOST]
SFTP_PORT=[Access port of HOST to connect]
SFTP_USER=[user account]
SFTP_PW=[user password]
SFTP_PRIVATE_KEY=[Access Key Path]
SFTP_ROOT_DIR=[root directory of connection destination]

3. SFTP communication

3.1 Implementation of SFTP communication

I will omit detailed processing, but I will describe reading of setting information and file upload by SFTP.

// Output SFTP settings to logger
logger()->info(get_class() .'SFTP HOST is['. Config::get('filesystems.disks.sftp.host') .']');
        
// storage setting for SFTP upload
$storageDir = storage_path() .DIRECTORY_SEPARATOR .'app' .DIRECTORY_SEPARATOR .'upload' .DIRECTORY_SEPARATOR;

//Upload sample.csv as new_sample.csv
$contents = file_get_contents($storageDir.'sample.csv');
Storage::disk('sftp')->put('new_sample.csv', $contents);

3.2 Deploy to each environment (production/dev)

I think that “2.1 Service Provider”, “2.2 File System” and “Process I created in 3.1” that I set myself are managed by git, but I have deployed the vendor and below in each environment. In my case, I did a git pull and put the composer.json and then ran composer install.

composer install

#in conclusion Although it was a long sentence, I described the introduction and setting of SFTP in Laravel and the deployment in each environment. Thank you for reading the contents summarized as a review of personal work until the end.

Reference site