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

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?

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) ...

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.

Related

PHP Timed bans?

I made a ban script where it updates the members list and put SET banned=Yes WHERE username=$_POST[username]
But now I would like to make timed bans, like if a user get banned for a day, he will be un-banned after his ban time.
Does anyone know how I could do this? I'm not pretty good with MySQL and times.
Simply change the column to something like "BannedUntil (datetime)" set that to one day into the future:
UPDATE Users SET BannedUntil = DATE_ADD(NOW(), INTERVAL 1 DAY) WHERE username = <username>
And to check if the user is banned
SELECT 1 FROM Users WHERE BannedUntil > NOW() AND username = <username>
If we get a row back, the user is banned, otherwise not.
You save the time of the ban, and the duration of the ban.
Pseudo-code:
if (current_date == ban_time + ban_duration) { unban_user }
Store the time when the user was banned and the duration of the ban. When the user attempts to access any page which needs to know whether he or she's banned or not - to display a "you're banned" message or whatnot - query the database for the user info. If he's banned, add the ban duration to the ban time and compare it to your current time. You can lift the ban if you've passed that computed time.
You must save ban time (unix timestamp field or datetime) and also duration of ban, when user try to login, you can simply check how much time passed after ban, if ban time passed, update row, and set banned column to 'No'

Change record automatically

On the website i'm developing i'm making a system for ban and unban users.
In my database i have a table 'banned' with fields about the bans (userID, active, date was made, reason ecc).
What i want to do is:
Add another field for expire date, and when this date occur, change automatically the field 'active' to 0.
How i can do that?
I would not use two fields like you did -- because I would not want to depend on a task to change back the active field when the un-ban date is reached.
Instead, I would only use one datetime field, called like banned_until; and this field would either:
Be NULL when the user is not banned,
Or contain the date until which the user is banned.
Then, when the user tries to do something (log-in, post, ...), I would check that :
This field is NULL, in which case the user is not banned
Or that the date contained in this field is in the past, in which can the user has been banned, but is no longer.
In the second case, you could even reset the field to NULL, as the un-ban date has been reached.
Its either you use a cron script or when getting banned users, you apply a where clause to check if the the ban has expired
Create a php script that will check if time is passed the expiration date. SQL will be something like this:
UPDATE banned SET active=0 WHERE expire_date<=NOW()
Save it as a for example task.php
Then create a cron task with crontab -e
*/10 * * * * php /path/to/your/taks/task.php
And this will cause this script to be executed every 10min and unban all banned ppl.
--
There are other ways, perhaps better ones, like e.g. Pascal described, but this answer is for your idea.
You can compare expiry_date value with current_date to check if a user is active or not on his login.
SELECT
( DATE_FORMAT( expiry_date_field, '%Y-%m-%d' )
<
DATE_FORMAT( CURRENT_DATE, '%Y-%m-%d' )
) AS isActive
FROM
banned
WHERE
user_id=?;
A 0 returned represents in-active status and 1 as active.
But irrespective of a user's login, if you want to maintain active status of users, you can achieve this using the Event Scheduler.
Following example gives you an idea in implementing one.
drop event if exists event_user_bans_scheduling;
delimiter //
create event if not exists event_user_bans_scheduling
-- on schedule every 86400 second starts 00:00:00
-- at timestamp( adddate( current_date, 1 ),'00:00:00' )
on schedule every 1 day starts timestamp( current_date + 1, '00:00:01' )
comment 'Scheduler to update active status of users'
do
UPDATE my_app_db.banned
SET ACTIVE=0
WHERE
date_format( expiry_date_field,'%Y-%m-%d' ) = date_format( CURRENT_DATE, '%Y-%m-%d' );
;
//
delimiter ;
Note:
The global event_scheduler system variable determines whether the Event Scheduler is enabled and running on the server. Read complete notes on Event Scheduler Configuration before working on MySQL events.

how to delete user if user doesnot attempt login within 30 days in php

i am new in php.. i want to delete the user automatically if he does not attempt login in 30 days.
for example
if user login on "10-02-2012" ,
and if user doesnot login for next 30 days
then system should automatically delete his account.
if user again login on "15-02-2012" ,
then limit should be for next 30 days i-e "15-03-2012"
please help me i am very new in php
i have no idea how to store the date when user attempt to login.
You want to have a date field in the user table and a query that sets that date to CURDATE() whenever your login script runs. Something like:
UPDATE 'users' SET 'lastlogin' = CURDATE() WHERE 'userid' = '$userid';
Have a crontab that runs once a day (or however often you want) that queries all the fields that are 31 days old and deletes them:
DELETE FROM 'users' WHERE 'lastlogin' < CURDATE() - INTERVAL 31 DAY
Log the last login date in a Database.
Write a script which searches and deletes users where the last login was more then 30 days ago.
start the search and delete script with a cron job
Here's a tutorial on building a login system:
http://www.phpeasystep.com/phptu/6.html
Your solution would add to the tutorial by adding a DATETIME field named "last_login" to the members table. Whenever someone logs in, you update the last_login field with a database query like:
UPDATE TABLE members SET last_login = CURRENT_TIME WHERE id = xxx LIMIT 1
Then you can run another database query once a day to delete inactive accounts, customizing the deletion date as needed:
DELETE FROM TABLE members WHERE last_login < '2012-04-01 00:00:00'
it's very simple.
create a field in the DB table that stores the most recent login date.
write a script run every night at midnight that checks the login date against the current date.
the great thing about this is date objects allow you to easily compare dates easily.
here are some links that will help:
http://php.net/manual/en/function.date.php
http://www.w3schools.com/sql/sql_dates.asp
best of luck! it's pretty straight forward I have done it many times im sure you wont have much trouble.
In your data base, where user accounts are stored, you can store the last time they logged in using one of the built in MySQL date/time data types. In your PHP you can update this to the current time with another MySQL command. This page will get you started: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
As for deleting a user, you will want to set up a cron job/scheduled task, that will delete this user by checking the date and seeing if it is 30 days ago.
You can add two field for users table
created : date when user registered
login_date: date update on every login by user.
And you can use cron Job which run automatically (run a php file which path set in it) on selected time. you can run it every day on a fixed time. and if found both created and login_date same then delete that user from database. You can set cron job from your cpanel.
thanks
set up cron job for once a day and check who didn't logged in from last 30 days to current time / date you can use timestamp or date for last login

Online or offline function PHP

I'm working on a "community". And of course I would like to be able to tell if a user is online or offline.
I've created so that when you log in a row in my table UPDATE's to 1 (default is 0) and then they're online. And when they log out they're offline. But if they don't press the Log out button, they will be online until they press that button.
So what I would like to create is:
After 5 minutes of inactivity the row in my database should UPDATE to 0.
What I'm looking for is how to do this the easiest way. Should I make an mysql_query which UPDATE's the row to 1 every time a page is loaded. Or is there another way to do it?
Instead of using a boolean "Online" field, use a DateTime. When a user makes a request to the page, update the DateTime to NOW(). When you are gathering your list of current users online, your WHERE clause would be something like WHERE lastSeen > DATE_SUB(NOW(), INTERVAL 5 Minutes)
Update: To retrieve individual online status.
select if(lastSeen > date_sub(now(), interval 15 minutes), 1, 0) as status from table where userid=$userid
This tutorial is quite handy: Who Is Online Widget With PHP, MySQL & jQuery
Well, if you don't want to set up a cron job, that would execute some code every 5 minutes, you have no options. But, actually, I think the following approach would be much more efficient:
Change your 1/0 column to timestamp
On each user request update that timestamp to current DateTime.
When checking for active users, check if that timestamp is less than 5 minutes from now
This way you'll be having actual data on users and no recurring queries - just one additional update per request
If you will update the row only on page load, then some of information would be incorrect.
Let's assume that user have opened page and is writing really long text or something. He is doing it for half an hour now. And your database ny now is already updated and he is counted as offline user.
I would write javascript that pings you back each 5 minutes, if opened tab is active.
This ping updates database field 'last_activity' to NOW(). And to count online users, or check if user is online you'll need to compare 'last_activity' to NOW() minus five minutes.
Simpliest ways (IMHO):
You can count sessions in session_save_path() dir.
you can store last visit timestamp in DB, and count rows with (timestamp > current_timestamp - somedelay).

PHP and SQL Social Networking - User Online

I want to set up online detection on my website.
I have a row in my user table where the last login datetime is stored. Every time a user visits the site, his login date updates and user online row sets to 1 (1 - online, 0 - offline).
How to change the online row to 0 (offline) if the last login was 10 or more minutes ago? The aim is to find difference between dates.
cronjob every 10 minutes?
UDPATE users SET online = 0 WHERE login_date > (NOW() - INTERVAL 10 minute);
just to each user add a last_seen timestamp to there row so that when you do your user is authed check you can update the time
if(logged_in())
{
update_user();
}
function update_user()
{
//UPDATE users SET last_seen = unix_timestamp() WHERE uid = X;
}
Then you can do for you users:
SELECT * FROM users WHERE last_seen > (unix_timestamp()-300)
To get the last 5 mins.
If you want to show the users who have been online within last 10 mins then the best method is to include the datetime condition in the sql query.
Save the last login time as timestamp, then you can easily compare it with the current time and tell how much time has passed since.
Depending on the size of your user table, you can run the check of those who are still supposedly online every time somebody calls your website.
A different approach is to store active users in buckets, labeled with the last login time, you can then easily reset all users that are in buckets older than 10 minutes.

Categories