2014-01-10 40 views
0

我有一个Web应用程序在服务器上运行,每个页面只允许一个用户。我想检查页面是否已被使用。如果ts是,我会改变旗帜的颜色为红色,并且在使用完成之前不允许进入。但我不知道我该怎么做。是一个PHP应用程序,我也在使用一些JavaScript。该应用程序已经完成,但我现在必须执行它。如何检查页面是否已被访问?如何检查页面是否已被访问?

+0

如果用户保存在你的数据库,然后保存在一个表的页面访问该用户,如果匿名用户再使用的cookie。 –

+0

您可以使用会话来存储关系users/bannercolor – zeflex

+3

如何定义何时页面“已被使用”?你如何定义何时“完成使用”?网页上是否采取了某种行动? –

回答

2
<?php 

session_start(); 

$lockfile = 'lock.txt'; 
$idleSeconds = 300; 



if(file_exists($lockfile)) 
{ 
    // read the file. 
    // $file[0] = timestamp of last page visit 
    // $file[1] = session id 
    $file = file_get_contents($lockfile); 
    $file = explode('|', $file); 

    // If the same user is visiting the site he shall pass and refresh the timestamp 
    // Do the same for a new user when the idletime ran out 
    if($file[1] == session_id() OR $file[0] + $idleSeconds <= time()) 
     file_put_contents($lockfile, time() .'|'. session_id()); 
    else 
     die("You are not allowed to view the page. Wait until some other motherfucker is done here.");  
} 
else 
{ 
    // When there's no lockfile create one for the current user 
    file_put_contents($lockfile, time() .'|'. session_id()); 
} 

?> 

<html> 
<head> 
    <title>My locked Page</title> 
</head> 
<body> 
    Yeah some cool shit man 
</body> 
</html> 

我很快为你拼凑了一些东西,以防万一你想要一个唯一的PHP方法。 我们正在这里使用lockfile。第一个访问该页面的用户将生成一个带有会话ID和当前时间戳的锁定文件。

我们检查每个请求是否存在锁定文件,如果是,我们检查用户是否被允许通过检查他的会话ID来查看页面。然后我们更新时间戳。

如果他不是我们检查空闲时间是否用完。如果是这种情况,我们可以覆盖日志文件,因为其他用户没有采取行动$idleSeconds

这是一个快速和肮脏的解决方案,但显示了基本的想法。

快乐编码;)

+0

我在想那样的事情是的。做得好 ! – zeflex

+0

这是无法避免的,总是存在一点点延迟。你可以减少$ idleSeconds到20或10,看看你是否感觉很好 – thpl

1

无论问题的背景是什么,我个人都不会创建一个导致这种需求的系统。但是,我会假设你别无选择。

一种方法是:

  1. 为了从客户端通过Ajax有页面上目前周期请求(初始触发是页负载,此后的Ajax)。

  2. 确保每个请求重新启动短定时器,让这个人更多的时间之前,其他人可以跳。

  3. 当计时器到期时,假设他们已经离开了该网页,因为Ajax请求已经停止。

有整洁的解决方案:Best way to detect when a user leaves a web page?

但是他们采取当用户完成从服务器,在理想情况下,你要保持它拿走决定的责任。