How to Make Short Random Unique Keys, Like Youtube Video Ids, in PHP

How can I make short random unique keys, like YouTube video IDs, in PHP?

The idea is to convert a unique integer (such as current time) in an other mathematical base.

A very simple way in PHP :

// With this precision (microsecond) ID will looks like '2di2adajgq6h'

// From PHP 7.4.0 this is needed, otherwise a warning is displayed
$cleanNumber = preg_replace( '/[^0-9]/', '', microtime(false) );
$id = base_convert($cleanNumber, 10, 36);

// With less precision (second) ID will looks like 'niu7pj'

$id = base_convert(time(), 10, 36);

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

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

create unique string in php with base_convert and limited length

Short Answer: No, but if you are doing something tiny like a personal website, or a internal only tool used by very few people it will be OK.

Long answer: Definitely not if you are trying to do something secure, or using multiple servers that share database. Attackers can figure out exactly how long it takes for their request to reach your server and bombard it with their requests until your server generates duplicate IDs if you rely on microtime.
uniqid function is not guaranteed to return uniq value(straight from php manual), and will definitely generate duplicate IDs if you are updating your time using NTP and it adjusts your time to 5 seconds ago.

Short Random Unique alphanumeric keys similar to Youtube IDs, in Swift

Looking for just a unique string

You can use UUIDs they're pretty cool:

let uuid = NSUUID().UUIDString
print(uuid)

From the  docs

UUIDs (Universally Unique Identifiers), also known as GUIDs (Globally
Unique Identifiers) or IIDs (Interface Identifiers), are 128-bit
values. UUIDs created by NSUUID conform to RFC 4122 version 4 and are
created with random bytes.

Some info about uuid: https://en.wikipedia.org/wiki/Universally_unique_identifier

Looking for a more specific length

Try something like this:

func randomStringWithLength(len: Int) -> NSString {

let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

let randomString : NSMutableString = NSMutableString(capacity: len)

for _ in 1...len{
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.character(at: Int(rand)))
}

return randomString
}

But i'll keep my answer incase someone else stumbles upon this looking for a UUID

PHP: Short id like Youtube, with salt

If you want to make the numerical id unguessable from the string, you can use a salt. You should be able to get the id back without collisions. The post Create short IDs with PHP - Like Youtube or TinyURL by Kevin van Zonneveld is a good start. At any rate, check for uniqueness.

Youtube-Like IDs (UrL) With Php and MysQL

Alright, first of all, your code you're using there is vulnerable.($_GET['id'] part) You should check out SQL Injection and sanitizing your code. The most important thing is to stay safe.

I'd start with making a unique name for your file first (cool looking, youtube style if that's what you're looking for.)

You can solve this in any way you like, here's my very simplistic example.

//if no errors
$name = $_FILES['file']['name'];//Our name
$temp = $_FILES['file']['tmp_name'];
$ext = pathinfo($name, PATHINFO_EXTENSION); //Get the extension before we make any changes.

$name =md5($name.microtime());//md5 of our name and microtime, this makes sure the encryption is random most of the time, because microtime is always changing.
$name = substr($name, 0,8); //Cutting off the part we don't need

move_uploaded_file($temp,"uploaded/".$name.'.'.$ext); //Storing out file

Now, lets add this to a database. -->

+----+----------+------+
| id | name | ext |
+----+----------+------+
| x | x5Wa88Bq | .mp4 |
+----+----------+------+

I made this database assuming you will always have a same path to your uploads, if not then you will have to go with a different solution.

 //?Selecting from database by id, if no errors     $name = $row['name'];

echo "You are watching ".$name."<br />";
echo "<video id='my_video_1' class='video-js vjs-default-skin'
controls preload='none' width='640px' height='267px' data-setup='{}'>
<source src='load.php?v=$name' type='video/mp4' /> </video>";

Now we should create a load.php file, which will actually point somewhere to our video.

load.php ->

$v = $_GET['v']; //Sanitise first, don't use like this.

//Compare with database, if true get name and extension
$name = $row['name'];
$ext = $row['ext'];
$url = 'http://localhost:8888/videouploadandplayback/uploaded/';

if(!empty($v)){
header("location:"$url.$name.$ext."");
}

Our load.php now checks if there is a video with a specific name (ex. x5Wa88Bq), since that file exists it points it to the correct directory. The code that handles the video realises that load.php?v=$name points to a video (or not) and plays it (doesn't).

Now if you want to do more 'styling', you can check out .htaccess guides. It will help you out with rewriting your URL's. And hopefully then you could do

<source src='$name' type='video/mp4' /> 

Cheers.



Related Topics



Leave a reply



Submit