by Devin Yang
(This article was automatically translated.)

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


laravel

After upgrading Laravel 8.8, I integrated the articles and notes together

Laravel 8 has undergone major revisions, and my website has also been revised accordingly. The "notes" and "articles" on my website were originally separated into two blocks. This time I integrated him together. Anyway, there are not many articles, and the combined content seems to be more. :p

laravel

How do I upgrade the backend to Lravel 5.5

At the beginning, my background was a framework created by myself, which also uses MVC architecture, database connections and environment configuration files made by myself, including my own template syntax, until I want to support Restful, I have an idea, why should I rewrite the same function myself after others have written it, would it be better to write it out? So I started to use the framework, At the beginning, Slim was adopted mainly because it supports a lower version of php, but because Slim's twig templates are not as easy to use as Laravel's blade template...

laravel,woops

Laravel 5.5 Woops is back, let's check it out.

Woops is a framework for PHP error handling. It was preloaded in Laravel 4, but it was removed in Laravel 5.0, and now 5.5 is back.... Some features of Whoops include: - Flexible, stack-based error handling - No dependencies are required to use the current stand-alone library - Simple API for handling exceptions, tracking frames and their data -Include a stunning error page within your web application - Includes the ability to open referenced files directly in editors and IDEs - Includes handlers for different response formats (JSON, XML, SOAP) -Easy to extend and integrate with existing libraries - Clean, well structured and proven generation