Hello,


What I am trying to do is restrict access to something if 48 hours hasn't passed since the last access.

I have a MySQL table with the last access time (col name: lastAccess).

If they are within the 48hours, deny access and tell them how many hours and minutes until they can access it again, otherwise, let them through,

Here is my not-working code.

$q = mysql_query("SELECT lastAccess FROM access");
$a = mysql_fetch_array($q);
$access = $a['lastAccess'];
if(strtotime("+48 hours", $access) >= time()){
	echo "Access Granted";
}else{
	echo "No Access! You have __ hours and __ minutes left.";
}

Thank you in advance for your help.

-- Turt2Live

Dani AI

Generated

Good start and nice direction from . A clearer, more robust approach is to convert the database value into a PHP DateTime, add a 48‑hour DateInterval, then compare to now. That avoids format and timezone surprises and makes it trivial to compute the remaining hours and minutes.

/* $row['lastAccess'] fetched from the database (DATETIME like "YYYY-MM-DD HH:MM:SS" or an integer epoch) */
$raw = $row['lastAccess'];

if (ctype_digit($raw)) {
    $last = new DateTime('@' . $raw);               // epoch -> UTC
    $last->setTimezone(new DateTimeZone('UTC'));
} else {
    $last = DateTime::createFromFormat('Y-m-d H:i:s', $raw, new DateTimeZone('UTC'));
    if ($last === false) {                          // fallback if format differs
        $last = new DateTime($raw, new DateTimeZone('UTC'));
    }
}

$unlock = clone $last;
$unlock->add(new DateInterval('PT48H'));

$now = new DateTime('now', new DateTimeZone('UTC'));

if ($now >= $unlock) {
    echo 'Access Granted';
} else {
    $diff = $now->diff($unlock);
    $hours   = $diff->days * 24 + $diff->h;
    $minutes = $diff->i;
    printf('No Access! %d hours and %d minutes left.', $hours, $minutes);
}

Notes and troubleshooting

  • Keep DB times and PHP comparisons in the same timezone (UTC recommended).
  • Handle null or missing lastAccess (treat as never accessed).
  • Prefer PDO or mysqli with prepared statements instead of deprecated mysql_* calls.
  • Update lastAccess only after a successful grant and consider atomic updates or transactions to avoid race conditions when requests occur concurrently.

Recommended Answers

All 3 Replies

MySQL returns dates and times in a different format than PHP, which uses timestamps. Use the MySQL function UNIX_TIMESTAMP to convert it in your query.

$q = mysql_query("SELECT UNIX_TIMESTAMP(lastAccess) FROM access");

Alright, and how would I determine the hours and minutes until the lock is over?

The rest of the code looked good for that, except the name of the array element would be UNIX_TIMESTAMP(lastAccess) so:

$access = $a['UNIX_TIMESTAMP(lastAccess)'];
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.