Reputation: 255
I'm building a fairly simple ticketing system in PHP where when a user purchases a ticket, they're emailed a PDF with a barcode attached, the barcode contains their order ID, which when scanned at the event, matches the ID of the order in the database and validates the ticket.
However, I don't want the order id to presented in plain text in the barcode, as somebody could simply create a barcode with one digit higher or lower than their own and then have a valid ticket. I've looked at MD5 and some other encryption algorithms, but they produce 64 bit alphanumeric strings, which aren't ideal, as there is a possibility of the need to type the number in rather than scanning it.
Ideally, an id would convert from something like 123 to 864374357, so it's still fairly simple for a human to type.
Any ideas on what the best method of creating a simple encryption like this would be?
Upvotes: 1
Views: 982
Reputation: 42063
You could generate a short unique number which is then stored in a separate column in the database. You could write a function like:
function generate_random_number($length) {
$random = '';
for($i = 0; $i < $length; $i++) {
$random .= rand(0, 9);
}
return $random;
}
And generate a unique number:
do {
$unique = generate_random_number(10);
$sql = "SELECT COUNT(*) FROM example_table WHERE unique_id = $unique";
$res = $conn->query($sql);
} while($res->fetchColumn() > 0);
echo $unique;
Upvotes: 0
Reputation: 572
Take a look at this question here, I think it will give you what you need!
Basically, just take the MD5 (or any algorithm) hash and then run a little extra processing on it to convert it to a numeric format, or limit its length.
Upvotes: 1