mikecao / shorty

A simple URL shortener for PHP
MIT License
271 stars 98 forks source link

How to generate fixed length key? #18

Open cuixiping opened 1 year ago

cuixiping commented 1 year ago

For example, always generate 6-chars key for id 1 to 1,000,000?

JMcrafter26 commented 1 year ago

There is no simple way of doing it, you need to dive into the code and rewrite it

PS: I made an ui for shorty: Here

cuixiping commented 1 year ago

There is no simple way of doing it, you need to dive into the code and rewrite it

PS: I made an ui for shorty: Here

The demo doesn't work.

JMcrafter26 commented 1 year ago

There is no simple way of doing it, you need to dive into the code and rewrite it PS: I made an ui for shorty: Here

The demo doesn't work.

There is a note saying that this is a demo and the demo doesn't work, please read that

cuixiping commented 1 year ago

There is no simple way of doing it, you need to dive into the code and rewrite it PS: I made an ui for shorty: Here

The demo doesn't work.

There is a note saying that this is a demo and the demo doesn't work, please read that

Your UI demo looks pretty! :+1:

JMcrafter26 commented 1 year ago

Hello, it's me again. I found a way that does this. In the config.php file there is a $padding variable. But it behaves strange, for example if you set it to 7 the length of the short link will be 5.

IMPORTANT: Changing the padding variable will permanently change all short links

cuixiping commented 1 year ago

Thank you for your research. Yes, the $padding is confusing. I set $padding=8;, tested from 1 to 50. Results of 1~9, 16, 27, 39 and 42 are 6 chars, others are 7 chars.

id     result
1   roa8l2
2   jxmktn
3   71f8bj
4   i9n61s
5   dq1gvt
6   okj96f
7   mr3zyb
8   qbvze1
9   r3lelx
10  25b5hpw
11  m5qiq92
12  2la55op
13  r433th3
14  2tv9uax
15  mjpk6hv
16  atao75
17  r6ojucu
18  mk1e7lm
19  oed6r5s
20  2g6741w
21  mks9ywf
22  2lbcrtn
23  r2tu8c1
24  m7rc3th
25  mjo6fx4
26  ogmiark
27  vuf6sq
28  d5vli7j
29  o3p9mes
30  mlxy1jv
31  drqvf9f
32  rffe9hp
33  r7uf1rj
34  2fjzl4s
35  2z2kpbw
36  o1ts189
37  m3qauie
38  ozfof3i
39  y9oa1l
40  otdzusg
41  29ssayc
42  vcvrho

I decided to use HashIds for php instead, which can generate fixed length key easily.

There are many implementations of HashIds.