如何允许用户仅在工作时间登录?

时间:2013-07-13 06:38:42

标签: php mysql

我想制作一个限制用户在下班后登录的代码: 用户只能从8:00到4:35登录: 贝娄是我尝试的代码,我设法使两个条件工作,但第三个条件不起作用:任何帮助将非常感激:

<?php
    # function to get right time of the targeted city
    date_default_timezone_set('Africa/Johannesburg');
    function time_diff_conv($start, $s)
    {
        $string="";
        $t = array( //suffixes
            'd' => 86400,
            'h' => 3600,
            'm' => 60,
        );
        $s = abs($s - $start);
        foreach($t as $key => &$val) {
            $$key = floor($s/$val);
            $s -= ($$key*$val);
            $string .= ($$key==0) ? '' : $$key . "$key ";
        }
        return $string . $s. 's';
    }
$date = date('h:i');
 echo  $date;
 /*Start time for work*/
 $workStart = strtotime("08:00");//am
  /*Stop time for work*/
 $workStop = strtotime("04:35");//pm
 /*This is the current time*/
 $currentTime = strtotime($date); 
 //$fromSatrtToEnd = $workStart->diff($workStop);
 /*This Condition works*/
 if($currentTime >=$workStart){
 echo "Start Working";
 /*This Condition also  works*/
 } else if($currentTime < $workStart){
 echo "You too early at work";
 }
 /*This Condition does not works*/
 else if($currentTime < $workStop){
 echo "Its after work";
 }

?>

3 个答案:

答案 0 :(得分:1)

if($currentTime >=$workStart AND $currentTime <= $workStop){
    echo "Start Working";
    /*This Condition also  works*/
} else if($currentTime < $workStart){
    echo "You too early at work";
}
/*This Condition does not works*/
else if($currentTime < $workStop){
    echo "Its after work";
}

如果时间是在开始时间之后,那么你的第一个条件总是如此。您需要检查它是否在时间范围内。

答案 1 :(得分:0)

你必须明确你的日期,程序无法识别08:00是AM日期,04:35是PM日期。

只需在

中更改变量声明即可
 /*Start time for work*/
 $workStart = strtotime("08:00 AM");//am
  /*Stop time for work*/
 $workStop = strtotime("04:35 PM");//pm

或将第二个变量转换为24小时格式:

$ workStop = strtotime(“16:35 PM”); // pm

$workStart相比,这种方式$workStop将被正确评估为次要值。

然后更改您的if以正确匹配条件:

if($currentTime >=$workStart && $current <= $workstop){
    echo "Start Working";
} else if($currentTime < $workStart){
    echo "You too early at work";
}
else if($currentTime > $workStop){ 
    echo "Its after work";
}

答案 2 :(得分:0)

首先,如果您必须管理上午/下午时间,您应该在使用它们的每一行中将小时数转换为24小时格式:

$date = date('H:i'); // H rather than h
$workStart = strtotime("08:00");
$workStop = strtotime("16:35");

你的条件不对,你应该有:

if($currentTime >=$workStart AND $current <= $workstop){ // need to check both
    echo "Start Working";
} else if($currentTime < $workStart){
    echo "You too early at work";
}
else if($currentTime > $workStop){ // > rather than <
    echo "Its after work";
}