Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a timed ban on an account? (PHP/mysql)

Tags:

php

mysql

I want to create a function that allows me to ban an account for 10days. In the dbc, I have a field called "ban" and Boolean of 1=notban, 0=ban. I also have a field called "date_banned" which is just the timestamp of when the user got banned.

My question is how do I create a time frame of 10days from the date the user was banned?

ex: James was banned on "2010-05-03 20:43:48". So how can I go about adding 10days to the timestamp? And after 10days, it would set the "ban" equal to 1(which is not banned).

EDIT: how can i show how many days the user has left of a ban? ex: 8 more days till unban

Can I...do NOW()-$date_banned? or how do I subtract the ban date from the current date?

like image 530
ggfan Avatar asked Dec 17 '22 00:12

ggfan


2 Answers

To add 10 days to your date_banned field in MySQL, you can simply use the DATE_ADD() function. You could do the following check when the user tries to log-in, to see if the ban has expired:

... WHERE NOW() > DATE_ADD(date_banned, INTERVAL 10 DAY);

Then you may want to toggle the ban field when the user tries to log in. Otherwise you can run a scheduled job every day, or at any other rate, that checks for expired bans and updates this field accordingly.

However you do not actually need the ban field to check if a user is banned or not. In fact you may want to consider eliminating it. Actually, I would go further and suggest to use a banned_until instead of date_banned (or use them both). The banned_until field would make your queries simpler, and would allow you to predefine arbitrary ban durations at the time the ban is issued. In this case, when a user logs in, you can simply do the following check:

... WHERE NOW() > banned_until;

UPDATE:

To get the number of days remaining until the end of the ban, you can use the TIMESPANDIFF() function in MySQL:

SELECT TIMESTAMPDIFF(DAY, NOW(), DATE_ADD(date_banned, INTERVAL 10 DAY)) ...

Or if you were to use the banned_until field, it will be even shorter:

SELECT TIMESTAMPDIFF(DAY, NOW(), banned_until) ...
like image 53
Daniel Vassallo Avatar answered Dec 28 '22 16:12

Daniel Vassallo


unban_date=DATE_ADD(NOW(), INTERVAL 10 DAY) should do the trick

Then just have a cron that checks to see if anybody's unban_date is in the past, and you can update your banned flag.

like image 34
Mitch Dempsey Avatar answered Dec 28 '22 16:12

Mitch Dempsey