0

如何让代码只运行一次。
我正在开发一个 zencart 网站,我想让 php 在用户第一次打开我的网站时更新网站设置信息,但之后不再运行这些代码。怎么做?

<?php 

    //how to let codes runs only one time.
    //cookie and session? 
    function first_time_run(){
        //lot of code runs when user  open my site at first time in browser (such  as ie ,firefox)
        //but when it go to other page of my site or reenter my same page ,these codes will not run any more;
        //but if user reopen the browser , then enter my site ,thes codes will runs again
    }

    if($what){
        first_time_run();
    }

?>
4

2 回答 2

1

使用会话变量。

if(isset($_SESSION['NEEDRUN'])){
 // run it
 // remove the session variable.
 unset($_SESSION['NEEDRUN']);
}

现在这将仅在设置会话变量时运行。

于 2012-12-30T08:02:26.357 回答
1

根据您的要求,shiplu 的解决方案可能会奏效。但是,如果您只希望代码运行一次(即客户第一次访问该站点时,做某事,然后再也不做),您需要在数据库中存储某种用户标识符。如果您只使用会话,一旦用户的会话结束(他或她离开站点、关闭浏览器等),则该会话变量不再存在。该客户下次访问该站点时,该脚本将再次运行。

You can also use a cookie that would persist after the user leaves the site, but still has limitations. Cookies have to have expirations (even if they are a year from now). When that cookie expires, that script will run again for the same customer. Additionally, a user can clear their cookies, use a different computer, etc and defeat your first_time_run check.

To conclude, the only lasting solution is to save some kind of customer identifier in a database and check that field whenever a user comes to your site.

于 2012-12-30T08:08:38.700 回答