Morteza Milani
Morteza Milani

Reputation: 1187

How to generate a hash string with some special rules in PHP?

I'm working on a project where I need to use some hash function to make a hash string. This hash string should be unique consists of 6 to 13 characters (fixed length).

I use a database to store data, so for each record, I have a unique ID. I want to use this unique ID to make a hash string ( to achieve uniqueness of resulted hash string).

I need this hash string to consists of only valid characters ( 0-9 a-z A-Z).

Which hash function should I use to achieve this goal? How can I generate such hash strings?

Added Later: I want to generate this string and pass it to user, so he can come back later to edit the entry. any other idea is acceptable.

Upvotes: 2

Views: 3235

Answers (3)

sarnold
sarnold

Reputation: 104050

Does it really need to be a cryptographic checksum? Or is a simpler checksum suitable? Is the database-provided primary key itself not suitable?

You've got lots of options, from the simplest crc32 to most-advanced sha512.

But if you're doing this for some specific application (such as filesystem hashing, or finding nearby objects using some metrics), then you're going to have to specify more of your problem.

Upvotes: 0

nebkat
nebkat

Reputation: 8565

Use crypt:

$hash = crypt("somevaluetohash", $uniqueid);

The unique id is a salt so you can generate different values depending on the id. So if one user had a password of "somevaluetohash" and another user had the same, the ending hash wouldn't be the same.

Upvotes: 3

phant0m
phant0m

Reputation: 16905

<?php
  $id;
  $hash_full = md5($id); //hash('sha256', $id);
  $hash_cropped = substr($hash_full, 0, 6);
?>

Use hash() for other hashing algorithms.

But what do you need this hashes for? To me, it doesn't make a lot of sense to generate a hash from the ID, couldn't you just use the ID instead?

Upvotes: 0

Related Questions