Pregunta

(PHP)

So here is what I would like to achieve.. but apparently I can't find any relevant information anywhere.

I would like my site to select a random value from my database every 5 minutes (for example: an ID from a table), and everyone that visit my site would see that same selected value, until the "server" randomly select another value 5 minutes after the last select.

So, I guess there would be a function that do the select from the database, but

1) where would I implement that function?

2) where would I call it? I'm not a expert in PHP, but I don't think it can be called from the client, else every client would call the function and they would not see the same value as others?

3) how do I to set a 5 minutes timer to call the function again?

In brief.

  • Server select a random value (ex: an ID from a table).

  • It get displayed on the site (same value from everyone for 5 minutes)

  • 5 minutes after last select, another value is randomly selected

  • It get displayed..

  • Repeat...

I will probably use Laravel to created my website, I'm saying just in case it's important for the solution.

Thank you for your help!!

¿Fue útil?

Solución

1) As far as implementing functions goes, It is pretty simple. If you need to use your function in multiple PHP documents, place int in a separate file and use an include to bring it into the document(that the client calls):

<?php include_once($_SERVER['DOCUMENT_ROOT']."/Path/To/file/phpscript.php");

If you only need it in one document, simple place it in in the document(that the client calls) before you use it.

2 & 3) There are "cron jobs" if you'r using Linux(I personally don't like using them), which could be used to awaken the php script every 5 minuets(in which case keep the function in its own file), but instead I would (edit: not, use cron jobs, this is a last resort)recommend another method instead. In your function(which will run when the client requests it), write the time you last requested it in to some text file, database or anything else. when the function runs, check if the written time was more than 5 minuets ago. If it was, create a new number and write a new time down. If it wasn't, fetch the old number from the database.

EDIT: Use Cron Jobs

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top