user3769279
user3769279

Reputation: 135

PHP how to make Youtube like id's for urls?

I'm making a website which people can publish posts. In my database each post has an ID like 1, 2, 3 etc. but I would like to change them, like using a hash like Youtube does.

For example instead of http://localhost/post/1

They would go to http://localhost/post/hu9NA827z

Is there a method like hashing the numbers and decoding it?

Upvotes: 1

Views: 1811

Answers (3)

Havenard
Havenard

Reputation: 27894

The sequence hu9NA827z is BASE64. Decoding it, you get a binary sequence of 6 bytes.

For instance:

base64_encode('123456') // = 'MTIzNDU2'
base64_decode('MTIzNDU2') // = '123456'

However, on YouTube, BASE64 is not being used to protect the information, its purpuse is just to serialize it into a human-readable ASCII format. The real message behind it is a 48-bit binary sequence.

This binary sequence is probably the encrypted version of what would be the video ID on a database, but what it really is only YouTube developers knows for sure and they certainly expect it to remain that way.

In your case, you could simply implement a similar system using one of the many two-way encryption methods offered in PHP like MCrypt that supports a lot of encryption algorithms of your choice including the very safe AES.

Upvotes: 1

Neme
Neme

Reputation: 26

Well, while you could encrypt/decrypt it doesn't make much sense (you're gonna make it slower without any real benefit). Waht you can do is to have the primary key in your DB to be a string and generate a hash for the id or add a new column with a unique index, save the hash there and search the posts by the hash column (and maybe keep the id for internal purposes). You can use complex algorithms or just md5(uniqid()), since this is not for security i wouldn't worry too much. Make sure that when creating a new post, the uniqueness is not being violated. Now you have another reason for an insertion to fail (the hash not being unique) so prepare for that.

Check: http://php.net/manual/en/function.md5.php http://php.net/manual/en/function.uniqid.php

Upvotes: 1

Patrick Fisher
Patrick Fisher

Reputation: 8064

Since there is no need for this hash to be secure, you can just use the PHP built-in hash function, md5(). I suggest using the timestamp as input:

$id = md5(time());

Just truncate it to make it shorter. I suggest you keep the original primary key an autoincrement integer and add this hash as a new column.

Upvotes: 1

Related Questions