Prevent Code or Function from Executing More Than

2019-08-27 00:28发布

Is there a way to prevent a code-block or a function within a code from running more than once even if I re-execute (or reload) the PHP file?

I mean, can I restrict someone from executing a php script more than once? I can't seem to find the way to do this.

4条回答
【Aperson】
2楼-- · 2019-08-27 00:48

If you are using sessions, then you can set a flag in the user's session array after the code has executed:

function doSomething(){

   if (empty($_SESSION['completed'])){
      //Do stuff here if it has not been executed.
   }

   $_SESSION['completed'] = TRUE;
}

You should also check the sesison variable to see if the task has been executed previously. This assumes that the user can accept a session cookie.

查看更多
倾城 Initia
3楼-- · 2019-08-27 00:53

I have an app that does that.

What we did was create a table in the db called version, and stored a version number in there. When the script is ran, it compared the version number in the database with that in the php script. And perform whatever it needs to "upgrade" it to the new version, and then updates the version number in the database.

Of couse, if the version table does not exist, the code will create it and mark it as storing version zero.

查看更多
女痞
4楼-- · 2019-08-27 01:02

Yes, you can use a $_SESSION variable to determine if the code has been executed. The session variable will be set until the user closes their browser. If you want to extend it further than that, you can set a cookie. Please see the following links for more details.

Session Variables

Cookies

查看更多
不美不萌又怎样
5楼-- · 2019-08-27 01:09

Just put a counter in the function. If the counter is greater that 0, then don't do anything. The counter variable should be static so it "remembered" across multiple calls.

function sample() {
     static $call_counter = 0;
     if ( $call_counter>0 ) {
         return;
     }
     ...
     $call_counter++;
 }

As for making sure a file is only executed once, just use "include_once()" instead of "include()".

查看更多
登录 后发表回答