PHP implementation of Nanoid, secure URL-friendly unique ID generator

Overview

Nanoid-php

Build Status FOSSA Status

A tiny (179 bytes), secure URL-friendly unique string ID generator for JavaScript

Safe. It uses cryptographically strong random APIs and guarantees a proper distribution of symbols.

Small. Only 179 bytes (minified and gzipped). No dependencies. It uses Size Limit to control size.

Compact. It uses more symbols than UUID (A-Za-z0-9_-) and has the same number of unique options in just 21 symbols instead of 36.

Thanks awesome ai and his nanoid, this package is a copy in PHP! If you like nanoid and you want to use it in PHP, try me :D

Install

Via Composer

composer require hidehalo/nanoid-php

Usage

Normal

The main module uses URL-friendly symbols (A-Za-z0-9_-) and returns an ID with 21 characters (to have the same collisions probability as UUID v4).

use Hidehalo\Nanoid\Client;
use Hidehalo\Nanoid\GeneratorInterface;

$client = new Client();

# default random generator
echo $client->generateId($size = 21);
# more safer random generator
echo $client->generateId($size = 21, $mode = Client::MODE_DYNAMIC);

Custom Alphabet or Length

echo $client->formattedId($alphabet = '0123456789abcdefg', $size = 21);

Alphabet must contain 256 symbols or less. Otherwise, the generator will not be secure.

Custom Random Bytes Generator

# PS: anonymous class is new feature when PHP_VERSION >= 7.0
echo $client->formattedId($alphabet = '0123456789abcdefg', $size = 21,
new class implements GeneratorInterface {
    /**
     * @inheritDoc
     */
    public function random($size)
    {
        //TODO: implemenation ...
    }
});

random callback must accept the array size and return an array with random numbers.

If you want to use the same URL-friendly symbols with format, you can get default alphabet from the url module:

Please see CoreInterface::random(...) for the core random API prototype and notes

Examples

Please see Examples for more information on detailed usage.

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Notice

If you have any issues, just feel free and open it in this repository, thx!

Credits

License

The MIT License (MIT). Please see License File for more information.

FOSSA Status

Comments
  • Deprecation notice:

    Deprecation notice: "Implicit conversion from float to int loses precision" on upgrade to PHP 8.1

    Detailed description

    Firstly, thanks for this great package :)

    The issue:

    After upgrading from PHP 8.0 to PHP 8.1, I receive the deprecation notice described in the title when trying to use this library to generate a nanoid.

    Minimal code to reproduce:

    use Hidehalo\Nanoid\Client;
    
    $client = new Client();
    $client->generateId(21, Client::MODE_DYNAMIC);
    

    Logged:

    [errno: 8192] Implicit conversion from float 5.977279923499917 to int loses precision
    

    Context

    I used this library to generate unique IDs for various entities.

    Possible implementation

    Explicitly converting to an int should fix this deprecation notice. The relevant code is in src/Core.php on line 13.

    Your environment

    PHP 8.1.0 running on local development server with php -s. Version of this library as described in composer.lock is:

                "name": "hidehalo/nanoid-php",
                "version": "1.1.8",
                "source": {
                    "type": "git",
                    "url": "https://github.com/hidehalo/nanoid-php.git",
                    "reference": "14187ab7a5affa34078b6a54df94176bb7a21227"
                },
    
    bug enhancement 
    opened by matt-harvey 5
  • Still getting deprecation notice for implicit conversion even after updating to v1.1.9

    Still getting deprecation notice for implicit conversion even after updating to v1.1.9

    Detailed description

    After updating to 1.1.9, I am still getting this deprecation notice.

    Implicit conversion from float 59.746165961027145 to int loses precision in /vendor/hidehalo/nanoid-php/src/Client.php on line 113
    

    Code to reproduce

    use Hidehalo\Nanoid\Client as Nanoid;
    
    $this->nanoid = new Nanoid();
    $this->nanoid->generateId(10)
    

    Context

    Using this to generate a default uniqueID for editorjs blocks from php

    Possible implementation

    Explicit int casting

    Your environment

    • PHP 8.1.1
    • hidehalo/nanoid-php 1.1.9
    bug help wanted good first issue 
    opened by betaSavvy 4
  • generateID should use Client settings as default

    generateID should use Client settings as default

    The Client is initialized with a size and a generator:

    public function __construct($size = 21, GeneratorInterface $generator = null)
    

    However when using the client, the size is mandatory to specify:

    public function generateId($size, $mode = self::MODE_NORMAL)
    

    It would make more sense to me if the $size parameter would be optional for generateId and default to whatever was specified in the client constructor.

    enhancement 
    opened by splitbrain 3
  • Composer install error

    Composer install error

    Detailed description

    Your requirements could not be resolved to an installable set of packages.
    
    Problem 1
    - Conclusion: don't install hidehalo/nanoid-php 1.1.1
    - Conclusion: don't install hidehalo/nanoid-php 1.1.0
    - Conclusion: remove paragonie/random_compat v9.99.99
    - Installation request for hidehalo/nanoid-php ^1.1 -> satisfiable by hidehalo/nanoid-php[1.1.0, 1.1.0-alpha, 1.1.1].
    - Conclusion: don't install paragonie/random_compat v9.99.99
    - hidehalo/nanoid-php 1.1.0-alpha requires paragonie/random_compat ^2.0 -> satisfiable by paragonie/random_compat[v2.0.0, v2.0.1, v2.0.10, v2.0.11, v2.0.12, v2.0.13, v2.0.14, v2.0.15, v2.0.16, v2.0.17, v2.0.2, v2.0.3, v2.0.4, v2.0.5, v2.0.6, v2.0.7, v2.0.8, v2.0.9].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.0].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.1].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.10].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.11].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.12].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.13].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.14].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.15].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.16].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.17].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.2].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.3].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.4].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.5].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.6].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.7].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.8].
    - Can only install one of: paragonie/random_compat[v9.99.99, v2.0.9].
    - Installation request for paragonie/random_compat (locked at v9.99.99) -> satisfiable by paragonie/random_compat[v9.99.99].
    

    Possible implementation

    Update the version constraint of paragonie/random_compat to ^2.0|~9.99

    Your environment

    Include as many relevant details about the environment you experienced the bug in and how to reproduce it.

    • Version used PHP 7.1
    bug 
    opened by jenky 3
  • fix: Normal mode now generate random id correctly

    fix: Normal mode now generate random id correctly

    Description

    Should only explicit cast on random index for alphabet array.

    Motivation and context

    To fix the bug caused by previous pull request #21 .

    In the previous pull request, It outputs the result with only underscore(the first value of the alphabet array) as the explicit casted random number is always 0

    for example:

    use Hidehalo\Nanoid\Client;
    
    $client = new Client();
    
    $result = $client->generateId(10);
    // $result = '__________'
    

    How has this been tested?

    Added 2 new assertions to make ensure that it does not generate the result with only underscore.

    Types of changes

    What types of changes does your code introduce? Put an x in all the boxes that apply:

    • [x] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    Go over all the following points, and put an x in all the boxes that apply.

    Please, please, please, don't send your pull request until all of the boxes are ticked. Once your pull request is created, it will trigger a build on our continuous integration server to make sure your tests and code style pass.

    • [x] I have read the CONTRIBUTING document.
    • [x] My pull request addresses exactly one patch/feature.
    • [x] I have created a branch for this patch/feature.
    • [x] Each individual commit in the pull request is meaningful.
    • [x] I have added tests to cover my changes.
    • [x] If my change requires a change to the documentation, I have updated it accordingly.
    bugfix 
    opened by betaSavvy 2
  • testing: fix Travis CI failed on PHP 8.1

    testing: fix Travis CI failed on PHP 8.1

    Description

    Fix Travis CI failed on PHP 8.1

    Motivation and context

    Fix #18 , it will make CI test pass.

    How has this been tested?

    Just travis configuration, it's needn't tests

    Types of changes

    What types of changes does your code introduce? Put an x in all the boxes that apply:

    • [x] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    Go over all the following points, and put an x in all the boxes that apply.

    Please, please, please, don't send your pull request until all of the boxes are ticked. Once your pull request is created, it will trigger a build on our continuous integration server to make sure your tests and code style pass.

    • [x] I have read the CONTRIBUTING document.
    • [x] My pull request addresses exactly one patch/feature.
    • [x] I have created a branch for this patch/feature.
    • [x] Each individual commit in the pull request is meaningful.
    • [ ] I have added tests to cover my changes.
    • [x] If my change requires a change to the documentation, I have updated it accordingly.
    testing bugfix 
    opened by hidehalo 2
  • Non-issue: Make consistent & improve readability

    Non-issue: Make consistent & improve readability

    Description

    This PR is only concerned with updating some of the code formatting to adhere to the PSR-2 Coding Style Guide. Additionally some spacing is applied to logical comparisons, shorthand ternaries and arithmetic operators to improve readability (if the latter is considered superfluous, subjective, or unwanted I'll remove those).

    Motivation and context

    It solves some PSR-2 violations and improves readability for some statements.

    Types of changes

    Coding Style Guide/formatting changes.

    Checklist:

    • [x] I have read the CONTRIBUTING document.

    • [x] My pull request addresses exactly one patch/feature.

    • [x] I have created a branch for this patch/feature.

    • [x] Each individual commit in the pull request is meaningful.

    • [x] If my change requires a change to the documentation, I have updated it accordingly.

    enhancement 
    opened by sjokkateer 1
  • fix: Implicit numeric conversion when generating id in normal mode

    fix: Implicit numeric conversion when generating id in normal mode

    Description

    Explicit cast to int to remove deprecation notice.

    Motivation and context

    Fixes hidehalo/nanoid-php#20

    How has this been tested?

    Ran composer test and passed all test.

    Types of changes

    What types of changes does your code introduce? Put an x in all the boxes that apply:

    • [x] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    Go over all the following points, and put an x in all the boxes that apply.

    Please, please, please, don't send your pull request until all of the boxes are ticked. Once your pull request is created, it will trigger a build on our continuous integration server to make sure your tests and code style pass.

    • [x] I have read the CONTRIBUTING document.
    • [x] My pull request addresses exactly one patch/feature.
    • [x] I have created a branch for this patch/feature.
    • [x] Each individual commit in the pull request is meaningful.
    • [ ] I have added tests to cover my changes.
    • [x] If my change requires a change to the documentation, I have updated it accordingly.

    The existing tests already covers the needed assertions.

    bugfix 
    opened by betaSavvy 1
  • typo: remove $ at begin composer command

    typo: remove $ at begin composer command

    Description

    remove $ at begin composer command

    Motivation and context

    github just release copy button on quote, if we have $ when user using copy button, they have to manually remove $

    nanophp

    opened by kocoten1992 1
  • Add license scan report and status

    Add license scan report and status

    Your FOSSA integration was successful! Attached in this PR is a badge and license report to track scan status in your README.

    Below are docs for integrating FOSSA license checks into your CI:

    opened by fossabot 1
  • add missing default params in formattedId()

    add missing default params in formattedId()

    Description

    Some really basic things are wrong, as far as I know: The formattedId() method was missing default params, so I added $alphabet = null and $size = 0. Also generateId() was calling random() without $alphabet, so I also added it.

    Motivation and context

    Not shure how how nobody noticed this... if the client is instantiated with a size:

    $client = new Client(6);
    

    and then do this:

    $id = $client->formattedId($alphabet);
    

    An exception is thrown because $size is missing:

    Too few arguments to function Hidehalo\Nanoid\Client::formattedId()
    

    Why? I already set the $size in the client.

    Same thing in generateId(), $alphabet is not passed to random() even if I already defined it.

    $this->core->random($this->generator, $size);
    

    How has this been tested?

    With care and attention to basic things.

    Screenshots (if appropriate)

    ?

    Types of changes

    What types of changes does your code introduce? Put an x in all the boxes that apply:

    • [x] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    I'm sure this is super important but I'm just trying to help and I have not idea what this checklist is about: exactly one patch, individual commit, branch for this patch and so on...

    Hope you can find the pull request useful.

    enhancement wontfix 
    opened by jonagoldman 1
Releases(1.1.12)
Owner
__hidehalo
Tons of graceful design, life is too short to get it. 🤷
__hidehalo
This package allows you to easily work with NanoID in your Laravel models.

Laravel Model UUIDs Introduction Huge thanks to Micheal Dyrynda, whose work inspired me to create this package based on laravel-model-nanoid but uses

Parables Boltnoel 3 Jul 27, 2022
Get the thumbnail of youtube and vimeo videos from the url. The returned information is ID and URL of the thumbnail

Video Thumbnail URL Get the thumbnail of youtube and vimeo videos from the url. The returned information is ID and URL of the thumbnail Installation I

Fernando Valler 2 Jan 22, 2022
This package provides a trait that will generate a unique uuid when saving any Eloquent model.

Generate slugs when saving Eloquent models This package provides a trait that will generate a unique uuid when saving any Eloquent model. $model = new

Abdul Kudus 2 Oct 14, 2021
Laravel Design Pattern Generator (api generator)

Laravel Design Pattern Generator (api generator) you can create your restful api easily by using this library and you can filter, sort and include elo

HusseinAlaa 2 Sep 25, 2022
Friendly prefixed IDs for Laravel models

Friendly prefixed IDs for Laravel models Prefixing an id will help users to recognize what kind of id it is. Stripe does this by default: customer ids

Spatie 139 Dec 25, 2022
Strongly typed settings for Laravel, includes built-in encryption and friendly validation.

Strongly Typed Laravel Settings Install composer require bogdankharchenko/typed-laravel-settings Model Setup namespace App\Models\User; use Illuminat

Bogdan Kharchenko 10 Aug 31, 2022
Create a downloads list - quick and easy. With categories and mobile friendly design

Simple downloads list plugin for wordpress Create a downloads list - quick and easy. With categories and mobile friendly design What is Simple downloa

Neofix 2 Dec 4, 2022
PHP Secure Headers

Secure Headers Add security related headers to HTTP response. The package includes Service Providers for easy Laravel integration. Version Installatio

null 431 Dec 26, 2022
MySecureVault is the most secure passwords, notes and files vault on the Internet.

MySecureVault MySecureVault is the most secure passwords, notes and files vault on the Internet. It has been developed with ultimate privacy and secur

MySecureVault 1 Jan 26, 2022
A multitool library offering access to recommended security related libraries, standardised implementations of security defences, and secure implementations of commonly performed tasks.

SecurityMultiTool A multitool library offering access to recommended security related libraries, standardised implementations of security defences, an

Pádraic Brady 131 Oct 30, 2022
This is a simple url bot validator made with laravel and react

?? This is a simple URL validator. Used Technologies React - Javascript framework Laravel - PHP framework Mysql - Relational database Installation Ins

Vanderson Telema 1 Oct 27, 2021
Manage meta data based on URL path within your app.

Laravel SEO Manager This package provides simple functionality to manage SEO tags based on URL path within your Laravel application. You can put the U

Michael Rubel 20 Oct 20, 2022
Laravel package for manage your URL redirects in database or other sources to get better SEO results

Laravel 8 and 9 package to manage URL redirections inside your Laravel application using different data sources. It allows a better SEO support for your Laravel site.

Siro Díaz Palazón 51 Sep 21, 2022
Barcode generator in PHP that is easy to use, non-bloated and framework independent.

PHP Barcode Generator This is an easy to use, non-bloated, framework independent, barcode generator in PHP. It creates SVG, PNG, JPG and HTML images,

Picqer 1.4k Jan 6, 2023
Html menu generator for Laravel

Html Menu Generator for Laravel This is the Laravel version of our menu package adds some extras like convenience methods for generating URLs and macr

Spatie 813 Jan 4, 2023
A Laravel and Lumen Badges Generator

Laravel and Lumen Badge Generator That package is a easy wrapper to Badges/Poser. #Installing composer require vluzrmos/laravel-badge-poser Laravel co

Vagner Luz do Carmo 6 Jun 10, 2020
A package for Laravel One Time Password (OTP) generator and validation without Eloquent Model, since it done by Cache.

Laravel OTP Introduction A package for Laravel One Time Password (OTP) generator and validation without Eloquent Model, since it done by Cache. The ca

Lim Teck Wei 52 Sep 6, 2022
Laravel Livewire (TALL-stack) form generator with realtime validation, file uploads, array fields, blade form input components and more.

TALL-stack form generator Laravel Livewire, Tailwind forms with auto-generated views. Support Contributions Features This is not an admin panel genera

TinaH 622 Jan 2, 2023
Promotional Codes Generator for Laravel >5

laravel-promocodes Promocodes generator for Laravel 5.*. Trying to make the best package in this category. You are welcome to join the party, give me

Zura Gabievi 425 Dec 26, 2022