PHP 可防止在页面刷新时重新加载数据



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

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

如何防止 ETL 脚本重新运行?对于此应用程序,没有理由刷新页面。如果可能的话,我应该简单地阻止该页面上的刷新吗?我可能忽略了一些简单的东西。所以,我愿意接受建议。

更新:

我得到了这个测试代码在索引.php页面上工作。因此,我将在此基础上制定解决方案。我会及时通知您。

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

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

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

  1. 因此,在您的 PHP 代码中(代替检查 $_SESSION),您将查询数据库以检索日期时间值
  2. 获得上次运行日期/时间后,您将检查当前日期/时间是否超过允许的"更新时间"(例如 24 小时)
  3. 如果时间超过您分配的"更新时间",例如 25 小时,代码将运行,您将日期时间更新为 now()
  4. 如果时间在分配的时间内,则不会发生任何事情,不会更新数据库,并且脚本不会运行。
  5. 重复 3 - 4。

上述方式将使用户数量无关紧要,因为所有检查都将针对中央数据集(即您的数据库)执行。它也可能会更健壮一些,因为它将独立于浏览器和用户。

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

<?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...................................................
?>

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

查看 POST/REDIRECT/GET 模式。(免责声明,我是那篇文章的作者

最新更新