Hi all, I need to send out an email to all the people on my email database and supply then with a coupon code, each needs to be unique. How can I do this? Open to any ideas…
Hi, I’ve managed to find the following code but want to understand what the following peice does, could some explain it to me…particularly don’t understand the use of square brackets here, thought these were only for arrays?
$string .= $characters[mt_rand(0, strlen($characters))]; //What does this do?
function genRandomString() {
$length = 10;
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
they are - nothing ever said you cant put functions inside of those square brackets.
Lets break the line down a bit.
$string .=
“To the variable $string append…”
$characters[
“A member of the $characters array with index…”
mt_rand(0,
“Generate a random number between 0 and…”
strlen($characters)
“The length of the $characters string”. (Note: A string may be referenced as an array of characters)
)];
(Close our functions and array definintions)
Does that clear it up?
(Incidentally, that code is bad, needs to be (strlen($characters) - 1) instead.)
This doesnt guarantee uniqueness, by the way.
Hey man, thanks for taking the time to reply to my post. Makes a lot of sense now, I did not realise you could access string characters in that manner…learn something new every day. You said the code is bad, apart from not having the -1 is it ok? Unsure of any other ways…
Other than that it’s not necessarily bad… it’s not incredibly cryptographic (capable of generating ‘aaaaaaaaaa’ as a string), and as said, doesnt necessarily generate a unique string if you’re generating a lot of them… though that functionality isnt too hard to add.
PHP is notorious for having a zillion PRNGs that only sort of work - most are seeded with “milliseconds since some-fixed-time” that can be easily guessed. If you want truly random, you need a CPRNG or a source of random data like random.org. When I need truly random, a good approach that I use is to have an internal secret string generated using random.org that gets concatenated with some not-so-random data generated using one of the PRNGs (mt_rand(), uniqid(), etc.) and then hash it using sha1() or md5(). The more data you can cram into the data to be hashed, the better off you will be security-wise. Don’t slice off bytes from a hash though - gotta use the whole thing.
That’s really the best you can do. But you have to ask yourself: Who is going to go after a custom-built coupon code generator that you need such security? IMO, as long as you aren’t planning on publishing the source code and simultaneously provide a URL to people showing them where exactly they can abuse it, I see no real problems with it other than the “-1” issue.
Why not just use a hash on the email?