Home > Back-end >  How to reset php srand function count?
How to reset php srand function count?

Time:08-04

I have the following instruction:

$seed = floor(time()/(60*1));
    srand($seed);
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $length = 8;
    $randomString = '';
    for ($i = 0; $i < $length; $i  ) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
     }

I'll put this inside a function, but that's not the problem. Well, basically it will generate random code with 1 minute expiration.

I need that after triggering a form this 1 minute count is reset to generate a new code. That is, if the user completes a certain action within 1 minute of triggering a form, he must generate a new code and not use the same code that was generated.

When the form fires the data is sent, then the page is reloaded. At this time I need the code not to be the same as the one sent previously.

Is this possible?

Update: In fact, I'm going to increase this time to 10 minutes, which is enough time for the user to complete a certain action on the page. What I'm doing is generating a unique id to write to the database when the form is triggered, this unique id will be used to look for images that will have this id at the beginning of the filename. It's basically a product image upload system.

CodePudding user response:

That is, if the user completes a certain action within 1 minute of triggering a form, he must generate a new code and not use the same code that was generated.

Do you mean if he doesn't complete the action within one minute? It sounds like you want the code to be valid for one minute only?

$seed = floor(time()/(60*1));

What's the purpose of (60 * 1) here?

Anyway, I'd not rely on rand() for purposes like this. Have a read of random_bytes() and see if that will fit your use case. Store the generated value and expiration as a session var or in the user's DB table (if there is one).

CodePudding user response:

Be clearer about what you want. It seems you are dividing (60*1) to be valid for one minute, if you want different code for every triggering (within one minute), you can use millisecond or other random mechanisms

  • Related