A small PHP library to generate YouTube-like ids from numbers.

Overview

hashids

Build Status Monthly Downloads Latest Version

Hashids is a small PHP library to generate YouTube-like ids from numbers. Use it when you don't want to expose your database numeric ids to users: https://hashids.org/php

Getting started

Require this package, with Composer, in the root directory of your project.

composer require hashids/hashids

Then you can import the class into your application:

use Hashids\Hashids;

$hashids = new Hashids();

$hashids->encode(1);

Note: Hashids requires either the BC Math or GMP extension in order to work.

Quick Example

use Hashids\Hashids;

$hashids = new Hashids();

$id = $hashids->encode(1, 2, 3); // o2fXhV
$numbers = $hashids->decode($id); // [1, 2, 3]

More Options

A few more ways to pass input ids to the encode() function:

use Hashids\Hashids;

$hashids = new Hashids();

$hashids->encode(1, 2, 3); // o2fXhV
$hashids->encode([1, 2, 3]); // o2fXhV
$hashids->encode('1', '2', '3'); // o2fXhV
$hashids->encode(['1', '2', '3']); // o2fXhV

Making your output ids unique

Pass a project name to make your output ids unique:

use Hashids\Hashids;

$hashids = new Hashids('My Project');
$hashids->encode(1, 2, 3); // Z4UrtW

$hashids = new Hashids('My Other Project');
$hashids->encode(1, 2, 3); // gPUasb

Use padding to make your output ids longer

Note that output ids are only padded to fit at least a certain length. It doesn't mean that they will be exactly that length.

use Hashids\Hashids;

$hashids = new Hashids(); // no padding
$hashids->encode(1); // jR

$hashids = new Hashids('', 10); // pad to length 10
$hashids->encode(1); // VolejRejNm

Using a custom alphabet

use Hashids\Hashids;

$hashids = new Hashids('', 0, 'abcdefghijklmnopqrstuvwxyz'); // all lowercase
$hashids->encode(1, 2, 3); // mdfphx

Encode hex instead of numbers

Useful if you want to encode Mongo's ObjectIds. Note that there is no limit on how large of a hex number you can pass (it does not have to be Mongo's ObjectId).

use Hashids\Hashids;

$hashids = new Hashids();

$id = $hashids->encodeHex('507f1f77bcf86cd799439011'); // y42LW46J9luq3Xq9XMly
$hex = $hashids->decodeHex($id); // 507f1f77bcf86cd799439011

Pitfalls

  1. When decoding, output is always an array of numbers (even if you encoded only one number):

    use Hashids\Hashids;
    
    $hashids = new Hashids();
    
    $id = $hashids->encode(1);
    
    $hashids->decode($id); // [1]
  2. Encoding negative numbers is not supported.

  3. If you pass bogus input to encode(), an empty string will be returned:

    use Hashids\Hashids;
    
    $hashids = new Hashids();
    
    $id = $hashids->encode('123a');
    
    $id === ''; // true
  4. Do not use this library as a security measure. Do not encode sensitive data with it. Hashids is not an encryption library.

Randomness

The primary purpose of Hashids is to obfuscate numeric ids. It's not meant or tested to be used as a security or compression tool. Having said that, this algorithm does try to make these ids random and unpredictable:

There is no pattern shown when encoding multiple identical numbers (3 shown in the following example):

use Hashids\Hashids;

$hashids = new Hashids();

$hashids->encode(5, 5, 5); // A6t1tQ

The same is true when encoding a series of numbers vs. encoding them separately:

use Hashids\Hashids;

$hashids = new Hashids();

$hashids->encode(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // wpfLh9iwsqt0uyCEFjHM

$hashids->encode(1); // jR
$hashids->encode(2); // k5
$hashids->encode(3); // l5
$hashids->encode(4); // mO
$hashids->encode(5); // nR

Curse words! #$%@

This code was written with the intent of placing the output ids in visible places, like the URL. Therefore, the algorithm tries to avoid generating most common English curse words by generating ids that never have the following letters next to each other:

c, f, h, i, s, t, u
Comments
  • Mac issues

    Mac issues

    Having this issue on 4 macs, but not on Ubuntu 14.04:

    All math libs are on, but when trying to use a number that has more than 10 digits I get a blank screen in the browser, without any errors (php error reporting is on, error logs remain empty).

    To fix it I have to make this change manually: private $_max_int_value = PHP_INT_MAX;

    or

    $this->_lower_max_int_value = PHP_INT_MAX;

    probably this variable $this->_lower_max_int_value must go after this block: if ($this->_math_functions) { $this->_max_int_value = PHP_INT_MAX; }

    and not before

    opened by oleghind 15
  • Missing BC Math or GMP extension

    Missing BC Math or GMP extension

    Hello. Just run into an issue on Heroku hosted app.

    Version 2.0.3 runs fine, version 2.0.4 crashes with this:

    RuntimeException
    
    Missing BC Math or GMP extension.
    
        /app/vendor/hashids/hashids/src/Math.php in mod at line 113
    
            if (function_exists('bcmod')) {
                return bcmod($n, $d);
            }
            throw new RuntimeException('Missing BC Math or GMP extension.');
        }
        /**
         * Compares two arbitrary-length integers.
         *
    
    d	100
    n	1
    

    It is confusing... by looking at the code it looks like version 2.0.3 would crash on "bad method call" or similar as well, but it really does not crash with 2.0.3. I'm using the

    I have not delved any deeper.


    The app is really simple and this is how I use hashids:

    		$hashFilters = [
    			Route::FILTER_IN => function($device) {
    				return $this->hs->decode($device)[0];
    			},
    			Route::FILTER_OUT => function($device) {
    				return $this->hs->encode($device);
    			},
    		];
    

    where $this->hs holds an instance of Hashids\Hashids class.

    opened by dakujem 14
  • Hashing both numbers (123) and (167) gives the same hashed id

    Hashing both numbers (123) and (167) gives the same hashed id

    Hello

    I'm generating hashed ids using the below:-

    (new \Hashids\Hashids('App\Booking' . 's1lt', 10))->encode(SOME_NUMBER)

    and i found that it generated two identical hashed ids although the numbers are different (123 and 167)

    so both (new \Hashids\Hashids('App\Booking' . 's1lt', 10))->encode(123) and (new \Hashids\Hashids('App\Booking' . 's1lt', 10))->encode(167)

    gives the hash Dkq1ZKnyWa

    Why is this happening ? Thanks in advance.

    opened by hazem-taha 12
  • Provide proper handling of arbitrary length integers

    Provide proper handling of arbitrary length integers

    Current version of library silently fails on numbers bigger than 32^2-1, but does require libraries which are needed only in this case.

    Results of encode() and decode() in this pull request are consistent with davidaurelio/hashids-python. encodeHex() and decodeHex() is still missing, as dechex/hexdec needs to be reimplemented.

    opened by jkramarz 12
  • Guessing the salt with a number of hashids

    Guessing the salt with a number of hashids

    I read somewhere that it could be possible to figure out the salt, with a good number of hashids. Like 30. Is this true?

    I am actually not really totally concerned, because we'll have other precautions set up for a proper API, but knowing this is true is simply good to know, in order add more precautionary steps to the API.

    Thanks for any insight.

    Scott

    opened by smolinari 10
  • v2.0.1 has changed encoded numbers

    v2.0.1 has changed encoded numbers

    $salt = 'this is my salt'; $minHashLength = 12; $hashids = new \Hashids\Hashids($salt, $minHashLength);

    v2.0.0 result var_dump($hashids->encode(1)); // returns DngB0NV05ev1

    v2.0.1 result var_dump($hashids->encode(1); // returns B0N444444Vd5

    Is this change intended?

    bug 
    opened by nitroshadow 9
  • Use separate Bc/Gmp math classes.

    Use separate Bc/Gmp math classes.

    I noticed that the current Hashids\Math class is making a function_exists check with each function call, which was quite slow. I've replaced it with a Hashids\Math\MathFactory that checks if the relevant extension (gmp/bcmath) is loaded instead, which returns a Hashids\Math\MathInterace class.

    I've tried to retain backwards compatibility by using the MathFactory inside the (deprecated, no longer used) Hashids\Math class as well.

    Here are a couple of blackfire.io profiles for encoding 50,000 hashes.


    🚨 A couple of things that need fixing/addressing:

    • Hashids\Math\Gmp and Hashids\Math\Bc can both be tested directly in the standard testsuite (tests/Math/MathInterfaceTest.php), so the disable_functions options in .travis.yml have been removed.
    • I couldn't figure out a way to disable extensions at runtime (either command-line or in PHP), so Hashids\Math\MathFactory is marked as @codeCoverageIgnore. 👎 (Considered adding a bitmask parameter to the constructor to force disabling GMP and/or BC, but is it worth it?)
    • tests/Hashids/RuntimeExceptionTest.php also can't be run properly, as there's no way to force disabling extensions at runtime. Could this test be removed instead? 🤷‍♂️
    enhancement 
    opened by jwpage 8
  • url as hash ?

    url as hash ?

    Hi,

    This look like a very nice library but I wonder if it's good to use a part of a url, or a uuid as hash.

    Can you give your opinion about this ?

    Thank you.

    opened by Yamakasi 8
  • Composer Compatibility Broken

    Composer Compatibility Broken

    Howdy,

    Wonderful package you got here. However, it looks like something changed recently.

    Problem 1
      - The requested package hashids/hashids 0.3.*@dev could not be found.
    
    Potential causes:
     - A typo in the package name
     - The package is not available in a stable-enough version according to your minimum-stability setting
       see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.
    
    Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.
    

    I wonder if you recently removed that branch or something. This causes my composer update to fail now.

    I'm using "hashids/hashids": "0.3.*@dev", but now it looks like I must change to "hashids/hashids": "dev-master"

    The problem with this though is that if you make any other backwards-incompatible changes I don't want to upgrade. Could you please re-add a version tag?

    Thanks.

    opened by dustingraham 8
  • hashids stopped encoding long string

    hashids stopped encoding long string

    am using current system time to make sure the created ids never collide

    system('date +%s%N')
    

    but recently the lib stopped working and started to give empty string instead, ex.

    Hashids::encode(1508058326172617500) // 20 digits
    

    will give "", but if we reduced the number

    Hashids::encode(150805832) // 9 digits
    

    it will work "bzeoONEa"

    any reason why this is happening ?

    btw testing the same long number on https://codepen.io/ivanakimov/pen/bNmExm works

    question 
    opened by ctf0 7
  • Remove BC Math Requirement

    Remove BC Math Requirement

    This pull request will remove the ext-bcmath requirement from the composer.json file. If you don't have installed BC Math but GMP installed you can't currently install this package. This pull request will solve that issue.

    This is still work in progress. The tests should pass and we want to keep our coverage at 100%.

    enhancement 
    opened by vinkla 7
  • Version 5.0

    Version 5.0

    This pull request is work in progress on the next major version of the package. I would say the package is feature complete and we should probably only add syntactic sugar such as type hints. I think we should probably stop supporting PHP 7 at some point. This PR is currently a playground for whatever idea comes to mind. Since this package is used by a lot of developers I want to hear what the community have to say. What can we improve?

    opened by vinkla 3
Releases(4.1.0)
Owner
Vincent Klaiber
Vincent Klaiber
#️⃣ Generate, Save, and Route Stripe-like Hash IDs for Laravel Eloquent Models

Using this package you can generate, save and, route Stripe-like Hash Ids for your Eloquent Models. Hash Ids are short, unique, and non-sequential, an

Yunus Emre Deligöz 88 Dec 27, 2022
A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

Jan Schädlich 69 Dec 18, 2022
Arc youtube - Youtube plugin for Textpattern

arc_youtube A Textpattern plugin for easily embedding Youtube videos in pages using a customisable player. This plugin works well with arc_vimeo and o

Andy Carter 5 May 17, 2018
This package provides a simple and intuitive way to work on the Youtube Data API. It provides fluent interface to Youtube features.

Laravel Youtube Client This package provides a simple and intuitive way to work on the Youtube Data API. It provides fluent interface to Youtube featu

Tilson Mateus 6 May 31, 2023
Michael Pratt 307 Dec 23, 2022
Xenon\LaravelBDSms is a sms gateway package for sending text message to Bangladeshi mobile numbers using several gateways like sslcommerz, greenweb, dianahost,metronet in Laravel framework

Xenon\LaravelBDSms is a sms gateway package for sending text message to Bangladeshi mobile numbers using several gateways for Laravel. You should use

Ariful Islam 95 Jan 3, 2023
Extracts information about web pages, like youtube videos, twitter statuses or blog articles.

Essence is a simple PHP library to extract media information from websites, like youtube videos, twitter statuses or blog articles. If you were alread

Essence 765 Dec 30, 2022
Laravel package allows you to generate a YouTube player from a video link.

Youtube Frame Generator Laravel package allows you to generate an iframe tag with a video player depending on a youtube URL. 1 - Dependency The first

Syrian Open Source 17 Nov 2, 2022
Simple PHP package for add two numbers

Sum Simple PHP package for add two numbers Installation To get the latest version of Sum, simply require the project using Composer: composer require

Nazar 13 Nov 20, 2022
This package is used to validate the telephone numbers of the countries taken into account. It also makes it possible to verify that a number is indeed a number of an operator X

phone-number-checker This package is used to validate the telephone numbers of the countries taken into account. It also makes it possible to verify t

faso-dev 4 Feb 7, 2022
Laravel package to convert English numbers to Bangla number or Bangla text, Bangla month name and Bangla Money Format

Number to Bangla Number, Word or Month Name in Laravel | Get Wordpress Plugin Laravel package to convert English numbers to Bangla number or Bangla te

Md. Rakibul Islam 50 Dec 26, 2022
This example shows how to estimate pi, using generated random numbers that uniformly distributed.

php-estimatepi This example shows how to estimate pi, using generated random numbers that uniformly distributed. Every pair of numbers produced will b

Oğuzhan Cerit 1 Nov 26, 2021
Composer addon to efficiently get installed packages' version numbers

Package Versions composer/package-versions-deprecated is a fully-compatible fork of ocramius/package-versions which provides compatibility with Compos

Composer 1.4k Dec 27, 2022
Code to accompany the YouTube video "Full PHP cURL API tutorial - how to use a REST API from PHP using cURL"

PHP cURL CRUD Example Example code to accompany this YouTube video. Note that the init_curl.php file contains a placeholder for an API key. DO NOT che

Dave Hollingworth 14 Dec 24, 2022
Small convention based CQRS library for PHP

LiteCQRS for PHP Small naming-convention based CQRS library for PHP (loosely based on LiteCQRS for C#) that relies on the MessageBus, Command, EventSo

Benjamin Eberlei 560 Nov 20, 2022
A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package.

Net A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package. Features: No hard dependencies; Favours

Minibase 16 Jun 7, 2022
A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package.

Net A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package. Features: No hard dependencies; Favours

Minibase 16 Jun 7, 2022
A small library to help run PHP servers easily and quickly.

PHP Server A small library to help run PHP servers easily and quickly. Installation composer require ahmard/php-server Usage PHP Built-In Server An i

Ahmad Mustapha 9 Dec 31, 2022
Small library providing some functional programming tools for PHP, based on Rambda

Functional library for PHP. Features: set of useful functions helpful in functional programming all functions are automatically curried every array ca

Wojciech Nawalaniec 5 Jun 16, 2022