Many article ids are regular and can crawl interface data or retrieve the content of the page

To prevent this from happening, we will use hashids encryption to generate irregular numbering

In this way, the data will not be crawled by people. I will demonstrate the detailed process below

Laravel – hashids dead simple url: https://github.com/vinkla/laravel-hashids

Install hashids in Laravel

Composer require vinkla/hashids v3.3.0Copy the code

PS: Since the latest vinkla/ Hashids version now supports 5.7, my Laravel version is 5.5, so I need the corresponding version number

Add it to the providers array in config/app.php

Vinkla\Hashids\HashidsServiceProvider::class,Copy the code

Add to the aliases array in config/app.php

'Hashids' => Vinkla\Hashids\Facades\Hashids::class,Copy the code

Config to generate the hashids.php configuration file

php artisan vendor:publishCopy the code

Change the salt value and encrypted output length for connections in hashids.php

Salt value can be any length of any character string, encryption and salt value has a direct relationship, salt value is the key to decryption. I directly take the key of the project as its salt value to make the project uniform and different projects have different encryption results.

'connections'= > ['main'= > ['salt' => env('APP_KEY'),
        'length'= >'6',].'alternative'= > ['salt'= >'your-salt-string'.'length'= >'your-length-integer',]],Copy the code

How Hashids are encrypted and decrypted

  • How encryption is used
Hashids::encode(123); // Returns the encrypted string o7gxkRCopy the code

  • Note that the return value is an array
Hashids::decode('o7gxkR'); Array (1) {[0]=> int(123456)}Copy the code

  • Encrypt multiple parameters simultaneously
Hashids: : encode (1, 2, 3); //KPCAigCopy the code

  • Decrypts an encrypted string for multiple arguments
Hashids::decode('M0BKxg8cYSNrVAjp'After decryption) / / return an array of array (3) {[0] = > int (1) [1] = > int (2) [2] = > int (3)}Copy the code

  • Switching different salt values and encryption lengths We may need to encrypt several different types of ids with different salt values and return lengths. So multiple arrays in the hashids of config can come in handy. The main array is the default connection, and you can add other encrypted arrays.
Hashids::connection('alternative')->encode(*);
Hashids::connection('alternative')->decode("* *");Copy the code

Pure original, all works are actual combat experience, hope to get everyone’s support.