Variable in PHP read by all clients

Asked

Viewed 102 times

3

Hello I want to have a control variable where the value of it is read by all customers and thus avoid that the same function is being executed by each client who enters the site.

Example, I have a page that updates the database with information.

If 10 people enter the site, this update will be performed 10 times.

If on the first visitor I can set a variable that can be read by the other visitors in order to prevent the update from being made again would be great.

You can do it?

3 answers

1

You can store the value in a file the first time you access it, and from there read the value from the file and avoid continuing to write.

$filePath = "/path/para/ficheiro";
if (!file_exists($filePath) {
    file_put_contents($filePath, "valor");
}
else {
    $valor = file_get_contents($filePath);
}

Alternatively you write once in the database and other times only write if the value does not yet exist. So only write once.

Taking into account one of the other answers, do not forget that the first option only works in 1 server mode, or if all servers share a folder where the file is located.

For solutions with more servers, the solution is to use a database to store this variable.

  • Could you give an example of how to do that?

  • @Rodrigo added the example for file use

  • Perfect, now I have another question. This is lighter for using server resources than changing a field in a mysql table and query this value for each client that visits the page?

  • @Rodrigo yes, files are lighter and faster than Mysql accesses

  • @Rodrigo Blunt’s answer is correct in generic terms, because the best solution will depend a lot on the server/servers environment that did not indicated in the question.

0

You shouldn’t put that kind of information into a variable. Imagine you have a server farm. You will have several instances of the same application running on separate machines so that variable is only one instance of your application is not shared this type of errors is common and serious.

  • 1

    What do you suggest then Marco? Thank you!

-1

I think what you’re looking for is this function: apc_store

For more information and examples: http://php.net/manual/en/function.apc-store.php

ATTENTION: you need to have Acp installed in PHP, if you use Ubuntu, just do:

# apt-get install php-acp
  • Although it is feasible, in my opinion it is a non-standard solution, as most providers do not provide APC

  • This is definitely a less positive feature... especially when you want to change hosts or something. But the idea is!

Browser other questions tagged

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