martin j martin j - 6 days ago 6
PHP Question

If server time is less then database row timestamp

I want to set a ban appeal time where if a user gets banned, I set a timestamp x hours or days in the future and only allow the user to login after the stored timestamp.

I set the server time using php so it follows local time, just to make sure people cant set their device date to a later date then the ban appeal time.

I have 1 column that checks if

ban = 1
and if it does I want to check another column called
ban_appeal
and compare it to the time and date of the server.

//check if user is banned
if($row['ban'] == 1){
if(if($server_date_time < $row['ban_appeal'])){
$login_ok = false;
die('
<div class="error-msg">
<i class="fa fa-times-circle"></i>
This user has not activated their account yet.
</div>
');
}
}

//server time
date_default_timezone_set('Europe/Oslo');
$server_time = date('h:i a', time());
$server_date = strtotime(date("Y-m-d"));


I'm 100% aware of that $server_date_time isnt set, but that is because im not sure how I should set it up to match a timestamp (
2016-11-27 02:33:51
)

Answer

Use built-in PHP DateTime object to handle time in different formats:

//server time
date_default_timezone_set('Europe/Oslo');
$server_date_time = new \DateTime();
$server_time = $server_date_time->format("h:i a");
$server_date = $server_date_time->format("Y-m-d");

//check if user is banned
if($row['ban'] == 1){
    // i'm expecting that ban_appeal date format is 2016-11-27 02:33:51
    $ban_date_time = \DateTime::createFromFormat("Y-m-d H:i:s", $row['ban_appeal']);

    if ($server_date_time < $ban_date_time) {
        $login_ok = false;
        die("User is banned until " . $ban_date_time->format("Y-m-d H:i:s"));
    }
}
Comments