Doubt - Generate 6 character random string in PHP

Asked

Viewed 249 times

0

Guys, how do I generate a string like this:

Z8Yjv.jpg

I went to get a photo of a user here from Stack-Overflow and the name of the photo came like this. I had thought of something like this:

<?php

$string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

echo substr(str_shuffle($string), 0, 6);

?>

What is the probability of generating the same string??... And if it is wrong in this way, then what is the best way to generate it???

  • 1

    There’s no point in doing that. Just use a Base64 (or other predictable criterion) from the database ID (or any sequential counter), which will never repeat.

  • @Bacco You’re right, I hadn’t even thought about it. hehe, thank you!

  • Another way is to do its own function, but it manages sequentially: a, b, c, .... , x, y, z, A, B, C, .... Z, aa, ab, ac, ad... Similar to what spreadsheets do with column identification. It continues in the same logic: you choose the characters, but convert from a numerical sequence that increments from 1 to 1, without repetition (which, at the end of the day, is exactly the same as URL shorteners and image stores usually do).

  • Good night! take a look at this link https://www.vivaolinux.com.br/script/String-randomica/

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.