繁体   English   中英

变量更改时运行PHP

[英]Run PHP when a variable changes

我的php代码有问题。 我想在变量更改时向数据库中添加一些内容。 我从另一个文件更改了一个变量。

在下面可以找到代码:

$urlMachineON = 'http://192.168.0.150/awp/Shredder/PLCfiles/IOmachineActive.html';

// get content
$contentMachineON = file_get_contents($urlMachineON);

//remove first 2 characters
$truncate = substr($contentMachineON, 2);

//remove last 5 characters
$MachineOn = substr($truncate, 0, -5);

if ($MachineOn == 0)
{
    echo "de machine staat uit";
    //Send information to the database
    //example: current time + MachineStatus(off) + message(Machine offline Error X)
}
elseif($MachineOn == 1)
{
    echo "de machine staat aan";
    //Send information to the database
    //example: current time + MachineStatus(on) + message(Error X is solved)
}

当我这样做时,它只会在刷新网页或使用某种按钮时在数据库中设置信息。 但这一定要自动进行。 因此,当变量$MachineOn从0变为1或从1变为0时,它必须在数据库中添加信息。 我该如何解决?

如果在同一执行过程中这种情况发生变化,则可以使用

static $previousMachineOn=$MachineOn;
if($previousMachineOn!=$MachineOn){
//changed
$previousMachineOn=$MachineOn;
//handle the change
}

如果在同一会话期间发生变化,则可以使用

$_SESSION['previousMachineOn']=(array_key_exists('previousMachineOn',$_SESSION)?$_SESSION['previousMachineOn']:$MachineOn);
if($_SESSION['previousMachineOn']!=$MachineOn){
//changed
$_SESSION['previousMachineOn']=$MachineOn
//handle the change
}

如果在执行期间或会话期间都没有改变,

if(file_get_contents("previousMachineOn.txt")!=$MachineOn)
{
//changed
file_put_contents("previousMachineOn.txt",$MachineOn,LOCK_EX);
//handle the change
}

或者也许您可以使用数据库或简单的文本文件,告诉它上一次更新的时间,如果太久以前就重新更新

if(file_get_contents("lastupdatetime.txt")-time()>1*60*60)
{
//more than 1 hour since last update.
//update lastupdatetime
file_put_contents("lastupdatetime.txt",time(),LOCK_EX);
//update code goes here
}

也许您可以拥有本地缓存​​的副本,并使用cronjob进行常规更新。.在这种情况下,您可能需要某种方法来处理cronjob删除文件的竞争状况,以便立即用更新的版本替换文件(我相信,使用LOCK_EX的file_put_contents应该可以解决问题,但是请注意,以我的经验,LOCK_EX在Windows * XP / 7操作系统上是躲闪的/不起作用的)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM