by Devin Yang
(This article was automatically translated.)

Published - 1 year ago ( Updated - 1 year ago )

Why do I separate the front and back of the website? My idea is very simple, that is to rely on a set of backend to control all the website data in the foreground.
Assuming that the front-end website is a purely marketing website, it is nothing more than the theme content, just like the above article, without any particularly complicated logic.
So the backend database should be set up and connected to different frontends. Then there is one last question, how can my backend HTML editor post pictures directly to the frontend?
Laravel’s Storage SFT Driver is Great antidote.

How to do it
Background part:
1. Install the sftp package in the background

composer require league/flysystem-sftp-v3 "^3.0"

Second, create an OpenSSH key pair in the background

dlaravel@05620df95284:~/html/storage/app$ ssh-keygen -t ed25519 -C "storage demo"
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/dlaravel/.ssh/id_ed25519): storage
storage already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in storage.
Your public key has been saved in storage.pub.
The key fingerprint is:
SHA256:LKl4GvrV+0Q9urecEtYfJPf7Cgha441TbUS4+r/1R/4 storage demo
The key's randomart image is:
+--[ED25519 256]--+
| .. |
| .. |
| .. |
| o .ooo |
| o So++ o. |
| . o *+B.+. . .|
| o + o.*oo....+ |
| . = o.+o..o..o|
|..o ..oo+oo..oE|
+----[SHA256]-----+
dlaravel@05620df95284:~/html/storage/app

3. Add

 'sftp' => [
            'driver' => 'sftp',
            'host' => env('SFTP_HOST'),
            // Settings for basic authentication...
            'username' => env('SFTP_USERNAME'),
            'privateKey' => env('SFTP_PRIVATE_KEY'),
            'passphrase' => env('SFTP_PASSPHRASE'),
            'port' => env('SFTP_PORT', 2258),
            'root' => env('SFTP_ROOT', '/var/www/html/storage/app'),
        ],

Fourth, we can cat the newly generated public key and copy it.

dlaravel@05620df95284:~/html/storage/app$ cat storage.pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPd1tsK2CqnRhVN5zbbJvi+Wpua+GWmbcazshpoRS0r7 storage demo
dlaravel@05620df95284:~/html/storage/app$ 

Fifth, add the public key to the front desk, because my front desk uses a deviny/phpenv container environment, so just put it in the authorized_keys on the host side.

Sixth, go back to the background host and adjust the .env as follows:
PORT part I wrote to death in the third step above config/filesystem.php, because it only eats numbers.

FILESYSTEM_DISK=sftp
SFTP_USERNAME=dlaravel
SFTP_HOST=192.168.99.2
SFTP_PASSPHRASE=demo
SFTP_PRIVATE_KEY=/home/dlaravel/html/storage/app/storage

Seventh, start, only use tinker to open the test, which is convenient, simple and easy to use.
Because the default file system uses sftp instead of local, so I don't need to add Storage::diks("sftp")
to type files to list the image files in the directory, which is easy to get done.

Eighth, the simpleUpload of CKEditor 5 that I use in the background, I used it in the Javascript part, jwt verification, and the file can only be uploaded after passing.

 simpleUpload: {
                    uploadUrl: '/image file upload path',
                    headers: {
                        'X-CSRF-TOKEN': '{{csrf_token()}}',
                        Authorization: 'Bearer {{$jwt}}'
                    }
                },

9. Part of the content of the Controller is as follows:

headers);
        $jwt_token = $request->bearerToken();
        //JWT verification but not to upload
        try {
            $decoded = JWT::decode($jwt_token, new Key($key, 'HS256'));
        } catch (\Exception $e) {
            abort(403);
        }
        //Only allow to upload jpg, bmp, png, gif
        try {
            $request->validate(['upload' => 'mimes:jpg,bmp,png,gif']);
        } catch (ValidationException $e) {
            Log::info($e->getMessage());
            return ["error" => ["message" => $e->getMessage()]];
        }
        //Upload to remote or local, depending on .env
        $path = Storage::putFile('public/images', $request->file('upload'));
        $url = Storage::url($path);
        // adjust the name
        if (env("FILESYSTEM_DISK") != "local") {
            $url = str_replace("public/", "storage/", $url);
            //Add the previous domain name
            $url = sprintf("%s/%s", env("DISK_URL"), $url);
        }
        return ["url" => $url];
    }
}

Come and see my screen directly, I copied and pasted the image file of this website like this: 😆
The domain name of this background website is notwww.ccc.tc哦, it is Another website, completely done through Laravel's Storage.

My other server management system backend also uses the function of adding queue through Storage,
directly upload all uploaded files to Google Drive
local one A copy of GoogleDrvie, my family's network architecture diagram: p

Laravel's official document, which can be opened from the following URL:
https://laravel.com/docs/9.x/filesystem#sftp-driver-configuration* 100080*

Tags: laravel sftp

Devin Yang

Feel free to ask me, if you don't get it.:)

No Comment

Post your comment

Login is required to leave comments

Similar Stories


dlaravel

How to set the external network IP to the Project on D-Laravel?

This video introduces how we assign Public Ip (public IP) to a specific Project in the D-Laravel environment. Whether it is the setting of the external production environment or the demo of your own project on the intranet, you can refer to the setting method of this video. In the video, although I used the external network IP of PPPoE dial-up to illustrate, we can also use the local network IP on our own computer if we change it. In this way, colleagues can connect to our D-Laravel Project.

d-laravel, docker, laravel, docker-compose

D-Laravel v1.0.0 release change description

In order to allow the container to be used more flexibly, D-Laravel has released version v1.0.0, which is not backward compatible. https://github.com/DevinY/dlaravel/releases/tag/v1.0.0 If you are using before v1.0.0, you need to modify the .env file of the Laravel project, change DB_HOST=127.0.0.1 to DB_HOST=db If you have a custom docker-compose-custom.yml file....more

laravel,docker

How to customize Laravel pagination

Recently, I have been free, and I want to adjust the arrows on the upper and lower pages of the website. If you don’t know how to customize Laravel’s pagination, You can take a look at a short three-minute introduction on how I customize Laravel's pagination.