Jacquiline Schipper
Jacquiline Schipper

Reputation: 1

multiple random numbers on one page /refresh

I'm trying to generate multiple unique hashes on one page and this script is not working. I keep getting only one number repeated 3 times instead of 3 unique numbers. I know i can create hash1, hash2, and hash3 functions but that is too much code.

<?php
  $seed = 'JvKnrQWPsThuJteNQAuH';
  $hash = sha1(uniqid($seed . mt_rand(), true));
  $hash = substr($hash, 0, 10);
?>

<? echo $hash; ?><br>
<? echo $hash; ?><br>
<? echo $hash; ?><br>

Upvotes: 0

Views: 414

Answers (5)

Eddy Freddy
Eddy Freddy

Reputation: 1816

<?php

function make_hash($seed = 'JvKnrQWPsThuJteNQAuH', $length = 16) {
    if (16 > $length) $length = 16;
    return substr(sha1(uniqid($seed . mt_rand(), true)), 0, $length);
}

?>


<?php

for ($i=0; $i<10; $i++) {
    echo make_hash('yourtexthere', 25);
    echo '<br>';
}

?>

Upvotes: 0

Sampson
Sampson

Reputation: 268354

You're only setting the value of $hash once, and then calling for that value three times. It looks to me like you want to create a function that generates a unique value:

function hash(){
  $seed = 'JvKnrQWPsThuJteNQAuH';
  $hash = sha1( uniqid( $seed . mt_rand(), true ) );
  return substr( $hash, 0, 10 );
}

echo hash() . '<br />';
echo hash() . '<br />';
echo hash();

If the seed isn't intended to be immutable, you could pass it in via a parameter:

function hash( $seed = 'defaultval' ) {
  $hash = sha1( uniqid( $seed . mt_rand(), true ) );
  return substr( $hash, 0, 10 );
}

echo hash( 'sEedOne' );
echo hash( 'seEDtWO' );
echo hash( 'SEed...' );

Upvotes: 2

donutdan4114
donutdan4114

Reputation: 1272

You need to make part of your code a function to call it multiple times.

function hash(){
  $seed = 'JvKnrQWPsThuJteNQAuH';
  $hash = sha1(uniqid($seed . mt_rand(), true));
  return substr($hash, 0, 10);
}

<? echo hash(); ?><br>

<? echo hash(); ?><br>

<? echo hash(); ?><br>

Upvotes: 2

Robot Woods
Robot Woods

Reputation: 5687

you can just make a function and then call that

<?php

function makeHash(){
    $seed = 'JvKnrQWPsThuJteNQAuH';
    $hash = sha1(uniqid($seed . mt_rand(), true));
    $hash = substr($hash, 0, 10);

    return $hash;
}

?>


<?php echo makeHash(); ?><br>

<?php echo makeHash(); ?><br>

<?php echo makeHash(); ?>

Upvotes: 4

rid
rid

Reputation: 63472

Regenerate $hash each time you need a new value. Otherwise, obviously, the variable you assigned the first random value to will have the same value no matter how many times you look at it, if the value is never changed.

Upvotes: 2

Related Questions