php阻止页面刷新时重新加载数据

时间:2012-06-13 03:00:21

标签: php page-refresh

我遇到问题 SIMILAR 阻止表单数据重新发布,但不完全相同。这个问题已被多次回答。给出的建议,如标题重定向和会话,对我来说不起作用。他们是否因为我的错误实施而失败,缺乏解决这个问题的经验,或两者兼而有之,我不知道。

我有一个Intranet Web应用程序,在启动时,从不同的服务器中提取数据,对其进行转换,然后将其加载到应用程序本地的数据库中。如果用户刷新主页面,则会再次运行ETL脚本并复制数据。

如何防止ETL脚本重新运行?对于这个应用程序,没有理由刷新页面。我是否应该在该页面上完全防止刷新,如果可能的话?我可能忽略了一些简单的事情。所以,我愿意接受建议。

更新:

我得到了这个测试代码来处理index.php页面。所以,我将在此基础上制定解决方案。我会告诉你的。

session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data

2 个答案:

答案 0 :(得分:2)

我已经为您概述了一个非常基本的示例,说明如何使用会话来确保每次访问(每个用户)只运行一次脚本。这里的关键点是,如果超过1个用户使用该系统,脚本仍会运行多次。

为了解决这个问题,我只需使用您的本地数据库来跟踪上次运行脚本的时间。因此,您可以在数据库中拥有一个日期时间列,以跟踪执行上次“运行”的时间。

  1. 因此,在您的PHP代码中(替换检查$ _SESSION),您将查询数据库以检索日期时间值
  2. 上次运行日期/时间后,您将检查当前日期/时间是否超过允许的“更新时间”(例如24小时)
  3. 如果时间已超过您的分配'更新时间',请说25小时代码会运行,您会将日期时间更新为现在()
  4. 如果时间在您的分配时间内,则不会发生任何事情,不会更新数据库,您的脚本也不会运行。
  5. 重复3 - 4。
  6. 上述方法会使用户数量无关,因为所有检查都将针对中央数据集(即您的数据库)执行。它也可能更健壮,因为它将独立于浏览器和用户。

    无论如何这里是一个会话(每个用户)方法:

    <?php
    /* 
     * Set PHP sessions to suit:
     * 
     * session.gc_maxlifetime is the number of seconds after which the data 
     * will be seen as garbage and cleaned up (session life) - 
     * 
     * Set to 86400 to in theory make the session last 24 hours - adjust this 
     * number to suit.
     * 
     * If this doesn't work you may have to try and adjust the php session lifetime
     * in either the php.ini file directly or htaccess file.
     * 
     */
    ini_set('session.gc_maxlifetime',86400);
    /* 
     * not strictly neccessary as this is default setting (but just to make sure)
     * This will keep the cookie alive (the link to your session) until the user
     * closes their browser. 
     * 
     * You could set it to > 86400 if you want that extra bit of certainity that 
     * the session will get renewed @ 24 hrs / the time you wanted to.
     */ 
    ini_set('session.cookie_lifetime',0);
    // Start PHP session
    session_start(); 
    
    // Check if the session is empty / exists (which it will be on first page entry)
    if ( empty($_SESSION['hasVisited']) ) {
    
      /* 
       * Add your ETL script logic here:
       * 
       * This will only run on the first visit to the site
       */   
    }
    
    // Now set the session as the scripts have run once
    $_SESSION['hasVisited'] = true;
    
    // Continue on with your app...................................................
    
    ?>
    

    如果我错过了您想要做的事情,或者您想要对任何事情做进一步解释,请告诉我?

答案 1 :(得分:0)

查看the POST/REDIRECT/GET pattern。 (免责声明,我是该文章的作者

相关问题