by Devin Yang
(This article was automatically translated.)

Published - 3 years ago ( Updated - 3 years 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


d-laravel, docker, docker-compose, laravel

D-Laravel released v0.9.1 version

In order to keep D-Laravel in an operational version and a stable version. Start tagging this version Pass those tests.. This version has passed the ubuntu real and macos real machine tests, and the Container can be successfully established and executed..

laravel,dotenv,seo

How do I dynamically load different dotenv files in Laravel according to the subdomain name

Before we start, let me complain. Originally, my website could automatically display different languages ​​according to the user's browser. That's okay, but Google's SEO doesn't seem to like it. He recommends using different URLs for each language and not using cookies or browser settings to adjust the content of the page. Well, I'll just be obedient. His suggested method, the first solution: distinguish by country, such as example.tw or example.de, how is this really impossible, or buy the registered domain name, or take all the domain names and no one will take it The strange domain name is more likely. The second solution: use sub-domain names to distinguish, this is what I am going to do, and so on to explain how to do it in Laravel. The third solution: example.com/tw/ and the like, Apple seems to do it this way. The fourth solution: site.com?loc=tw and the like are not recommended, indeed I think this is not a good idea.

laravel

Basic application teaching of jenkins CI Server pipeline on Laravel

Do you want to build a continuous integration and delivery CI Server for Laravel through docker? Execute laravel dusk and phpunit on CI Server to easily handle automated testing and related records. After reading this article, you may find out how simple CI/CD is. I mean basic use.